Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Be an Overachiever

Session 유지 방식 및 생성 시점 본문

Spring

Session 유지 방식 및 생성 시점

devson119 2018. 8. 25. 18:27
Spring 세션을 어떻게 유지하는지 그리고 세션이 언제 생성되는지 알아보자
 
세션은 어떻게 유지될까?
HTTP 특징 하나는 stateless이다. 클라이언트가 요청하고 서버가 응답하고 끝이다. 클라이언트와 서버가 서로 연결 상태로 있지 않다는 것이다.
그럼 서버는 어떻게 해당 클라이언트 요청에 대한 세션을 구분하고 관리하는 것일까?
힌트는 쿠키 있다.
 
설명 하기 전에 naver 로그인을 쿠키를 확인해보면
(크롬의 경우 주소창 왼쪽을 클릭하여 쿠키를 확인 있다.)


naver.com에 쿠키 목록이 있는데 여기에서 NID_SES 삭제하면 로그인이 풀린다.
 
세션의 동작방식은 서버에서 해당 요청에 대한 세션 객체와 세션 쿠키를 생성하고
요청이 들어올 해당 세션 쿠키를 통해 요청에 대한 세션을 구분하는 것이다.
톰캣의 경우 JSESSIONID 라는 쿠키가 있는데 이것이 세션을 유지시켜주는 역할을 한다.
(역시 쿠키 목록에서 JSESSIONID 제거하면 세션 유지가 풀린다)
 
 
그럼 세션은 언제 생성 될까?
주로 세션을 사용할 컨트롤러에서 HttpServletRequest 객체에서 getSession() 메서드를 사용한다.
getSession 메서드는 parameter boolean 넣을 있다.
마우스를 갖다대서 메서드를 확인해보자.
 
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
 
메서드는
  • true 파라미터에 넣을 경우 (getSession() getSession(true) 같다)
                @RequestMapping 통해 들어온 HttpServletRequest 해당하는 HttpSession 객체가 있다면
 해당 HttpSession 객체를 리턴하고 없다면 새로운 HttpSession 생성한다.
  • false 파라미터에 넣을 경우
                @RequestMapping 통해 들어온 HttpServletRequest 해당하는 HttpSession 객체가 있다면
해당 HttpSession 객체를 리턴하고 없다면 null 리턴한다.
 
세션에 대해 간단히 확인해보자.
Web dependency 추가한 Spring Boot 프로젝트를를 생성 다음과 같은 RestController 하나 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@RestController
public class SessionController {
 
    // 아무 것도 안함
    @GetMapping("/nothing")
    public String nothing() {
        return "HelloWorld";
    }
     
    // getSession(false) 호출
    @GetMapping("/sessionFalse")
    public String sessionFalse(HttpServletRequest request) {
        return request.getSession(false!= null ? 
            "session created" : "session not created";
    }
 
    // getSession(true) 호출
    @GetMapping("/sessionTrue")
    public String sessionTrue(HttpServletRequest request) {
        return request.getSession(true!= null    ? 
            "session created" : "session not created";
    }
 
    // getSession() 호출
    @GetMapping("/session")
    public String session(HttpServletRequest request) {
        return request.getSession() != null ? 
            "session created" : "session not created";
    }
 
}
cs

/nothing /sessionFalse 경우 아무리 호출해도 HttpSession 객체가 생성되지 않고 쿠키에 JSESSIONID 역시 생성되지 않는다. 하지만 /sessionTrue, /session 경우 바로 HttpSession 객체와 쿠키에 JSESSIONID가 생성되고 이후 쿠키에 JSESSIONID 제거하지 않는 계속 세션이 유지된다.


Comments