사용자 편의를 위해 아이디를 기억해뒀다가 다음에 로그인할때 쿠키기능 사용.
-> 로그인 성공 후 쿠키에 이메일을 저장하고, 웹 브라우저를 닫더라도 삭제되지 않도록 유효시간을 길게 설정한다.
@CookieValue 애노테이션은 요청 매핑 애노테이션 적용 메서드의 Cookie타입 파라미터에 적용한다. 쿠키를 view 페이지로부터 쿠키 파라미터로 전달 받을 수 있다.
@Controller
@RequestMapping("/login")
public class LoginController {
private AuthService authService;
public void setAuthService(AuthService authService) {
this.authService = authService;
}
//쿠키를 전달받는 메서드
@GetMapping
public String form(LoginCommand loginCommand, @CookieValue(value="REMEMBER", required=false) Cookie rCookie){
if(rCookie !=null) {
loginCommand.setEmail(rCookie.getValue());
loginCommand.setRememberEmail(true);
}
return "login/loginForm";
}
}
@PostMapping
public String submit(LoginCommand loginCommand, Errors errors, HttpSession session, HttpServletResponse response) {
new LoginCommandValidator().validate(loginCommand, errors);
if(errors.hasErrors()) {
return "login/loginForm";
}
try {
AuthInfo authInfo = authService.authenticate(loginCommand.getEmail(), loginCommand.getPassword());
session.setAttribute("authInfo", authInfo);
//실제 쿠키생성을 처리하는 부분!
Cookie rememberCookie = new Cookie("REMEMBER", loginCommand.getEmail());
rememberCookie.setPath("/");
if(loginCommand.isRememberEmail()) {
rememberCookie.setMaxAge(60*60*24*30); //쿠키 30일동안 유지
}else {
rememberCookie.setMaxAge(0); //이메일 저장에 동의하지 않을 경우 쿠키 삭제
}
response.addCookie(rememberCookie); //ModelAndView에 함께 가지고 갈 response 설정
return "login/loginSuccess"; //view 리턴
}catch (WrongIdPasswordException e) {
errors.reject("idPasswordNotMatching");
return "login/loginForm";
}
}
쿠키의 이름이 REMEMBER이며, 쿠키가 존재하면 email 프로퍼티에 쿠키값이 채워져서 출력된다.