컨트롤러에서 HttpSession 사용하기

방법1. 컨트롤러 메서드에 HttpSession 파라미터 추가

-   HttpSession 을 생성하기 전이면 새로운 HttpSession을 생성해서 파라미터로 전달하고, 그렇지않으면 기존에 존재하는 HttpSession을 전달한다.

방법2. 컨트롤러 메서드에 HttpServletRequest 파라미터를 추가하고 HttpServletRequest#getSession()

-   HttpServletRequest#getSession() 호출 시에, HttpSession 생성 전이면 HttpSession 을 생성한다.

세션 이해하기

로그인 예를 들어보자.

1 브라우저가 로그인 요청을 보냄
2 서버에서 아이디, 비밀번호를 확인한 다음,
1 세션 키를 생성한다.
2 해당 세션 키에 대응하는 저장소를 생성한다.
3 세션 키를 담은 쿠키를 응답으로 내려준다. (응답 헤더 Set-Cookie)
4 이후 브라우저가 요청을 보낼 때 요청의 쿠키 헤더에 해당 Session 키를 담아서 보냄
5 요청 헤더 쿠키의 Session key 사용

(session key = J SESSION ID 인듯)

인터셉터 사용하기

1 HandlerInterceptor 인터페이스 구현하기

다음은 springframework.web.servlet.HandlerInterceptor 인터페이스이다.


public interface HandlerInterceptor {

    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            @Nullable ModelAndView modelAndView) throws Exception {
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            @Nullable Exception ex) throws Exception {
    }
}

preHandle

  • HandlerMapping 이 요청 url을 이용해 컨트롤러 찾아준 이후, DispatcherServlet 이 HandlerAdaptor 에게 처리요청을 하기 전

postHandle

  • HandlerMapping 이 처리를 수행하고 ModelAndView 를 return 한 이후, DispatcherServlet이 View 에게 응답 생성 요청을 하기 전

afterCompletion

  • 클라이언트에게 응답이 전송된 이후

2 설정파일에서 인터셉터 객체를 Bean 등록하기

package config;

import ...

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {

    ...

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authCheckInterceptor())
            .addPathPatterns("/edit/**");
    }

    @Bean
    public AuthCheckInterceptor authCheckInterceptor() {
        return new AuthCheckInterceptor();
    }
}

출처

세션 이해하기

https://m.blog.naver.com/PostView.nhn?blogId=good_ray&logNo=221360993022&proxyReferer=https:%2F%2Fwww.google.com%2Fblog.naver.com/good_ray/221360883685

+ Recent posts