로그인시에 메인화면에서 로그인 상태가 유지되도록 쿠키를 생성하고 쿠키 존재 여부에 따라서 메인화면 로그인 버튼을 로그아웃 버튼으로 바뀌도록 코드를 작성했다.
<a class="btn btn-primary" href="#"th:href="@{/login}"role="button" th:if="${#request.getCookies()== null}">Login</a>
<a class="btn btn-primary" th:href="@{/logout}" role="button" th:if="${#request.getCookies()!= null}">Logout</a>
이렇게 타임리프의 조건문 기능 ( th:if )과 타임리프에서 제공하는 기본객체( {#request} )를 이용해서 쿠키의 여부에 따라 화면에 출력되는 버튼이 달라지도록 하였다.
@PostMapping("/main")
public String login(Member member, BindingResult bindingResult, HttpServletResponse response) {
try {
String userId = member.getUserId();
String password = member.getPassword();
Member byUserId = memberService.findByUserId(userId);
String id = String.valueOf(byUserId.getId());
log.info("-----------");
log.info(id);
if (loginRepository.login(userId, password)) {
log.info("로그인 성공1");
Cookie idCookie = new Cookie("memberId",id);
response.addCookie(idCookie);
//쿠키로 로그인 상태 유지
log.info("로그인 성공2");
return "redirect:/main";
} else {
log.info("로그인 실패-----------------");
bindingResult.reject("loginFail", "아이디 비밀번호가 맞지 않습니다.");
return "sign/login";
}
} catch (NullPointerException e) {
return "sign/login";
}
}
@GetMapping("/logout")
public String logout(HttpServletResponse response) {
expireCookie(response,"memberId");
return "redirect:/";
}
private void expireCookie(HttpServletResponse response, String cookieName) {
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
response.addCookie(cookie);
log.info("쿠키 지우기------------------------");
}
Controller 구현은 최근에 김영한 spring-mvc-2 에서 배운 내용을 토대로 작성하였다.
로그인 성공시에 response에 쿠키를 만들어서 넣고, 로그아웃을 요청받으면 새로운 쿠키를 만드는데, 유효시간을 0으로 설정해서 response에 넣는 방식으로 쿠키를 제거했다.
로그인을 완료했을 때 쿠키가 생성된 걸 바로 인식하지 못하고 새로고침을 했을 때 적용이 되는 문제를 redirect 를 이용해서 해결했다.
로그아웃 버튼을 누르면 로그인 창으로 이동하면서 쿠키를 제거한다.
+ 추가
<form class="d-flex" th:action="@{/order/cart}">
<a class="btn btn-primary" href="#"th:href="@{/login}"role="button" th:if="${#request.getCookies()== null}">Login</a>
<a class="btn btn-primary " th:href="@{/logout}" role="button" th:if="${#request.getCookies()!= null}">Logout</a>
<a class="btn btn-outline-dark active" th:href="@{/myPage}" role="button" th:if="${#request.getCookies()!= null}">MyPage</a>
<button class="btn btn-outline-dark" href="#" type="submit">
<i class="bi-cart-fill me-1"></i>
Cart
<span class="badge bg-dark text-white ms-1 rounded-pill">0</span>
</button>
</form>
mypage 버튼까지 로그인 여부에 따라 출력 되도록 하였다.
마이페이지에 접속하면 서버에서 유지하고 있는 memberId 값만 뜨게 하고 페이지를 구현하진 않았다. 마땅한 오픈소스를 못 찾아서 여기까지만 구현할 생각이다.