[SPRING] 13. MVC3-3 : 쿠키

Yuri Lee·2022년 7월 8일
0

스프링

목록 보기
10/13

컨트롤러에서 쿠키 사용하기

사용자 편의를 위해 아이디를 기억해뒀다가 다음에 로그인할때 쿠키기능 사용.
-> 로그인 성공 후 쿠키에 이메일을 저장하고, 웹 브라우저를 닫더라도 삭제되지 않도록 유효시간을 길게 설정한다.

@CookieValue 애노테이션

@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 프로퍼티에 쿠키값이 채워져서 출력된다.

profile
개발자 이유리

0개의 댓글