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
'프로그래밍 > SPRING' 카테고리의 다른 글
09. MVC 2 - 커맨트 객체 값 검증 및 에러 메시지 처리 (0) | 2022.08.03 |
---|---|
08. MVC 1 - 컨트롤러, 뷰 구현 (0) | 2022.08.02 |
07. Spring Web MVC (0) | 2022.08.01 |
06. AOP (0) | 2022.04.26 |
05. DI 적용 (0) | 2022.04.24 |