[JSP] - 쿠키와 세션(Cookie and Session)

세션(Session)

서버(Server)에 클라이언트의 상태 정보를 저장하는 기술로서 웹 서버에 클라이언트에 대한 정보를 저장하고 클라이언트에는 클라이언트를 구분할 수 있는 ID를 부여하는데 이것을 세션아이디(Session ID)라 한다.

 

대표적으로 클라이언트 정보 중 로그인 정보를 세션에 담아 저장하는 예제는 다음과 같다.

<%
    // 로그인 성공 시
    String userId = "user01";
    HttpSession session = request.getSession();
    session.setAttribute("userId", userId);
%>

 

<%
    HttpSession session = request.getSession();
    
    // 만약 해당 세션이 없다면 null을 반환합니다.
    String userId = (String) session.getAttribute("userId");
    
    if (userId == null) {
        // 로그인하지 않은 상태일 때 처리
        out.println("로그인하지 않았습니다.");
    } else {
        // 로그인한 상태일 때 처리
        out.println("환영합니다, " + userId + "님!");
    }
%>

 

쿠키(Cookie)

쿠키는 클라이언트(Clinet) 로컬에 저장되느 키와 값(Key, Value)이 들어있는 데이터 파일이다.

쿠키는 클라이언트의 상태 정보를 로컬에 저장했다가 요청할 때 참조된다.

 

<%
    // 로그인 성공 시
    String userId = "user01";
    Cookie cookie = new Cookie("userId", userId);
    
    // 쿠키의 유효 시간 설정 (예: 60*60은 1시간)
    cookie.setMaxAge(60*60); 
    
    response.addCookie(cookie);
%>
<%
    Cookie[] cookies = request.getCookies();
    String userId = null;

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("userId")) {
                userId = cookie.getValue();
                break;
            }
        }
     }

     if (userId == null) {
         // 로그인하지 않은 상태일 때 처리
         out.println("로그인하지 않았습니다.");
     } else {
         // 로그인한 상태일 때 처리
         out.println("환영합니다, " + userId + "님!");
     }
%>

 

<차이점>

쿠키 : 클라이언트의 local(PC)에저장
세션 : 서버메모리에 저장