본문 바로가기

Spring

HttpSession 사용 방법 사용 이유

728x90
반응형

HttpSession은 둘 이상의 Page Request에서 사용자 식별 혹은 사용자 정보를 저장하기 위한 방법을 제공함.

Spring Web MVC에서 HttpSession을 주입할 때 내부적으로 Servlet Container 에게 Session을 요청함.

 

 

 @GetMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute("name", "hi");
        httpSession.setAttribute("introduce", "myname  is..");

        return "setSession";
    }

    @GetMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();

        log.debug("SessionId : {}", session.getId());
        log.debug("session name : {}", session.getAttribute("name"));
        return "getSession";
    }
  • request.getSession(true) : 이미 세션이 있으면 세션을 돌려주고 없으면 새로운 세션을 생성한다.
  • request.getSession(false) : 세션이 있으면 세션을 주고 없으면 null을 돌려준다. 

 

JESSIONID

  • 톰캣 컨테이너에서 세션을 유지하기 위해 발급하는 키로 이 값을 통해 세션을 유지함.
  • 브라우저 최초 접근시 톰캣은 response header에 JESSIONID를 발급해서 던진다.
  • 브라우저 재요청시 JESSIONID를 Request header의 쿠키에 넣어서 서버에 요청
  • 유지되는 범위 : Full Domain(서브도메인은 X)
728x90
반응형