
다음은 호두 스케쥴러(Hodoo Scheduler)의 회원가입 / 로그인 부분이다.

회원가입 시 DB에 중복된 아이디가 있는지 확인하는 기능을 넣었다.
(※ UserServiceImpl 클래스의 idCheck 메서드)



@SessionAttributes("loginUser")
@Controller
@RequestMapping("/user")
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
super();
this.userService = userService;
}
@PostMapping("/login")
public String loginUser(UserDTO userDTO, Model model, HttpSession session) {
String page = "redirect:/";
System.out.println(userDTO);
try {
UserDTO loginDTO = userService.loginUser(userDTO);
model.addAttribute("loginUser", loginDTO);
session.setAttribute("msg", "로그인 성공!");
} catch (Exception e) {
page = "common/errorPage";
session.setAttribute("msg", "로그인 실패!");
e.printStackTrace();
}
return page;
}
@GetMapping("/register")
public String register() {
return "user/registerform";
}
@PostMapping("/register")
public String insertUser(UserDTO userDTO, HttpSession session) {
String page = "";
try {
int result = userService.insertUser(userDTO);
if (result > 0) {
session.setAttribute("msg", "회원가입 성공!");
page = "redirect:/";
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
session.setAttribute("msg", "회원가입 실패!");
page = "common/errorPage";
}
return page;
}
@RequestMapping("/logout")
public String logout(SessionStatus status) {
status.setComplete();
return "redirect:/";
}
@RequestMapping("/idCheck.do")
@ResponseBody
public int idCheck(UserDTO userDTO) throws Exception {
System.out.println(userDTO);
int result = 0;
UserDTO checkId = userService.idCheck(userDTO);
if (checkId != null) {
result = 1;
}
return result;
}
}
@Service
public class UserServiceImpl implements UserService {
private SqlSessionTemplate sqlSession;
private UserDAO userDAO;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public UserServiceImpl(SqlSessionTemplate sqlSession, UserDAO userDAO,
BCryptPasswordEncoder bCryptPasswordEncoder) {
super();
this.sqlSession = sqlSession;
this.userDAO = userDAO;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
public UserDTO loginUser(UserDTO userDTO) throws Exception {
String encpw = userDAO.selectEncryptedPwd(sqlSession, userDTO);
if (!bCryptPasswordEncoder.matches(userDTO.getPw(), encpw)) {
throw new Exception("패스워드 불일치, 로그인 실패");
}
UserDTO loginDto = userDAO.loginUser(sqlSession, userDTO);
if (loginDto == null) {
throw new Exception("loginUser 정보 확인, 로그인 실패");
}
return loginDto;
}
@Override
public int insertUser(UserDTO userDTO) throws Exception {
String encpw = bCryptPasswordEncoder.encode(userDTO.getPw());
userDTO.setPw(encpw);
int result = userDAO.insertUser(sqlSession, userDTO);
return result;
}
@Override
public UserDTO idCheck(UserDTO userDTO) throws Exception {
UserDTO loginDto = userDAO.loginUser(sqlSession, userDTO);
return loginDto;
}
}
@Repository
public class UserDAO {
public UserDTO loginUser(SqlSessionTemplate sqlSession, UserDTO userDTO) {
return sqlSession.selectOne("userMapper.selectUser", userDTO);
}
public int insertUser(SqlSessionTemplate sqlSession, UserDTO userDTO) {
return sqlSession.insert("userMapper.insertUser", userDTO);
}
public String selectEncryptedPwd(SqlSessionTemplate sqlSession, UserDTO userDTO) {
return sqlSession.selectOne("userMapper.selectEncryptedPwd", userDTO);
}
}
public class UserDTO {
private String userId;
private String pw;
private String name;
private String phone;
private Date createdDate;
private String isDeleted;
private Date delDate;
public UserDTO() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public Date getDelDate() {
return delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
@Override
public String toString() {
return "UserDTO [userId=" + userId + ", pw=" + pw + ", name=" + name + ", phone=" + phone + ", createdDate="
+ createdDate + ", isDeleted=" + isDeleted + ", delDate=" + delDate + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="userMapper">
<resultMap type="userDTO" id="userResultSet">
<!-- 언더바가 들어가는 쿼리문에 한하여 매핑을 해줘야함 -->
<id property="userId" column="user_id" />
<result property="pw" column="pw" />
<result property="name" column="name" />
<result property="phone" column="phone" />
<result property="createdDate" column="create_date" />
<result property="isDeleted" column="isdeleted" />
<result property="delDate" column="del_date" />
</resultMap>
<select id="selectUser" parameterType="userDTO"
resultMap="userResultSet">
SELECT *
FROM USER
WHERE user_id = #{userId}
</select>
<select id="selectEncryptedPwd" parameterType="userDTO"
resultType="java.lang.String">
SELECT
PW
FROM USER
WHERE user_id = #{ userId }
</select>
<select id="selectTaskList" parameterType="userDTO">
SELECT *
FROM TASK
WHERE user_id = #{ userId}
</select>
<insert id="insertUser" parameterType="userDTO">
INSERT
INTO USER
(user_id,
pw, name, phone)
VALUES (#{ userId }
, #{ pw }
, #{ name }
, #{ phone })
</insert>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- SQL문 정의할 때 VO표현을 간단하게 하고 싶은 경우. 별명을 지어서 사용 -->
<settings>
<setting name="jdbcTypeForNull" value="NULL" />
<!-- DB 조회결과 snake_case -> camelCase 변환 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeAliases>
<typeAlias
type="com.multi.hodooScheduler.user.model.dto.UserDTO"
alias="userDTO"></typeAlias>
<typeAlias
type="com.multi.hodooScheduler.task.model.dto.TaskDTO"
alias="taskDTO"></typeAlias>
<typeAlias
type="com.multi.hodooScheduler.diary.model.dto.DiaryDTO"
alias="diaryDTO"></typeAlias>
<typeAlias
type="com.multi.hodooScheduler.diary.model.dto.PageDTO"
alias="pageDTO"></typeAlias>
</typeAliases>
<mappers>
<!-- SQL문 정의하는 파일들의 목록을 지정. 테이블당 한개 사용 -->
<mapper resource="mapper/userMapper.xml" />
<mapper resource="mapper/taskMapper.xml" />
<mapper resource="mapper/diaryMapper.xml" />
</mappers>
</configuration>
[메인 이미지 출처] https://timeruler100.co.kr/2024%EB%85%84-%EB%8B%AC%EB%A0%A5-%EB%AC%B4%EB%A3%8C-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C%EC%97%91%EC%85%80%EC%84%9C%EC%8B%9D-2/
본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.