프로그래밍/SPRING
10. MVC 3 - 세션, 인터셉터, 쿠키
토요일
2022. 8. 4. 00:10
728x90
HttpSession
- 로그인 유지
//요청 매핑 애노테이션 적용 메서드에 HttpSession 파라미터 추가
@PostMapping
public String form(LoginCommand loginCommand, Errors errors, HttpSession session) {
...
}
// 항상 HttpSession 추가
// 요청 매핑 애노테이션 적용 메서드에 HttpServletRequest 파라미터를 추가하고
// HttpServletRequest를 이용해서 HttpSession을 구함
@PostMapping
public String submit (
LoginCommand loginCommand, Errors errors, HttpServletRequest req) {
HttpSession session = req.getSession();
...
}
// 필요한 시점에만 HttpSession 추가
로그인
- session.setAttribute("authInfo", authInfo);
로그아웃
- session.invalidate();
HandlerInterceptor
- HttpSession에 값이 존재하는지 검사하고 존재하지 않으면 다른 경로로 리다이렉트
boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception;
void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception;
void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authCheckInterceptor())
.addPathPatterns("/edit/**");
// /edit/으로 시작하고 0개 또는 그 이상의 파일 경로
}
@CookieValue
- 자동 로그인
// 생성
Cookie rememberCookie =
new Cookie("REMEMBER", loginCommand.getEmail());
remeberCookie.setPath("/");
if (loginCommand.isRememberEmail()) {
rememberCookie.setMaxAge(60 * 60 * 24 * 30); // 유효기간 한 달
} else {
rememberCookie.setMaxAge(0);
}
response.addCookie(rememberCookie);
@GetMapping
public String form(LoginCommand loginCommand,
@CookieValue(value="REMEMBER", required = false) Cookie cookie) {
if(cookie != null) {
loginCommand.setEmail(cookie.getValue());
loginCommand.setRememberEmail(true);
}
return "login/loginForm";
}
728x90