![[TiStory] 회원가입, 로그인, 로그아웃](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog%3Ftitle%3D%255BTiStory%255D%2520%25ED%259A%258C%25EC%259B%2590%25EA%25B0%2580%25EC%259E%2585%252C%2520%25EB%25A1%259C%25EA%25B7%25B8%25EC%259D%25B8%252C%2520%25EB%25A1%259C%25EA%25B7%25B8%25EC%2595%2584%25EC%259B%2583%26logoUrl%3Dhttps%253A%252F%252Finblog.ai%252Finblog_logo.png%26blogTitle%3DCoding_study&w=2048&q=75)
우선, 비밀번호 확인은 추후 ajax를 통해서 할 것이기 때문에 생략하고 진행한다.
1. 회원가입 - 화면확인

2. UserRequest - JoinDTO생성
@Data public static class JoinDTO { private String username; private String password; private String email; public User toEntity() { return User.builder() .username(username) .password(password) .email(email) .build(); } }
3. UserJPARepository - 유저 중복 조회 쿼리
@Query("select u from User u where u.username = :username") Optional<User> findByUsername(@Param("username") String username);
4. UserService
- 회원가입 시 트랜잭션 처리를 통해 유저를 등록
@Transactional public User join(UserRequest.JoinDTO reqDTO){ // 유저네임 중복검사(서비스 체크) - DB 연결이 필요함 Optional<User> userOP = userJPARepo.findByUsername(reqDTO.getUsername()); // isPresent가 있으면 비정상 if (userOP.isPresent()) { // 유저 중복 throw new ApiException400("중복된 아이디입니다."); // 예외처리 } // 아닌 경우 정상적으로 저장 User user = userJPARepo.save(reqDTO.toEntity()); return user; }
중복되면 메세지 뜸

4. UserController
@PostMapping("/join") public String join(UserRequest.JoinDTO reqDTO){ User sessionUser = userService.join(reqDTO); // 회원가입 후 바로 로그인 session.setAttribute("sessionUser", sessionUser); return "redirect:/"; }
회원가입 후 바로 로그인할 수 있게 구현
5. 쿼리 날라가는지 확인

6. DB 데이터 확인

7. 로그인 - 화면확인

8. UserRequest - LoginDTO생성
@Data public static class LoginDTO { private String username; private String password; }
9. UserJPARepository
// 로그인용 쿼리메소드 Optional<User> findByUsernameAndPassword(String username, String password);
10. UserService
public User login(UserRequest.LoginDTO reqDTO){ User sessionUser = userJPARepo.findByUsernameAndPassword(reqDTO.getUsername(), reqDTO.getPassword()) .orElseThrow(() -> new Exception401("아이디 혹은 비밀번호를 확인해주세요.")); // orElseThrow 값이 null이면 이라는 뜻 return sessionUser; // 세션에 저장 }
Exception 으로 던지기…
11. UserController
@PostMapping("/login") public String login(UserRequest.LoginDTO reqDTO) { User sessionUser = userService.login(reqDTO); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; }
12. 쿼리 확인


13. 로그아웃
@GetMapping("/logout") public String logout() { session.invalidate(); return "redirect:/"; }
Share article