쿠키(Cookie)와 세션(Session)

2024. 5. 23. 09:24Back-End/Spring

웹 애플리케이션에서 상태를 유지하기 위한 대표적인 두 가지 방법이 쿠키(Cookie)세션(Session)이다. 쿠키와 세션은 사용자의 상태를 유지하고, 사용자 맞춤형 경험을 제공하는 데 중요한 역할을 한다. 이 글에서는 쿠키와 세션의 개념, 차이점, 그리고 스프링에서 이를 사용하는 방법을 예제와 함께 설명하겠다. 또한, Thymeleaf를 사용하여 데이터를 웹 페이지에 표시하는 예제도 포함한다.

쿠키(Cookie)

쿠키는 클라이언트 측(사용자의 웹 브라우저)에 저장되는 작은 데이터 조각이다. 서버가 클라이언트에게 전송하며, 클라이언트는 이후 요청 시 이 쿠키를 함께 전송하여 서버가 사용자를 식별할 수 있게 한다.

 

쿠키의 특징:

  • 클라이언트 측에 저장됨
  • 용량 제한이 있음 (대개 4KB 이하)
  • 만료 시간을 설정할 수 있음

쿠키 설정 예제:

1. 컨트롤러에서 쿠키 설정:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class CookieController {

    @GetMapping("/setCookie")
    public String setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("username", "JohnDoe");
        cookie.setMaxAge(7 * 24 * 60 * 60); // 1 week
        response.addCookie(cookie);
        return "cookieSet";
    }

    @GetMapping("/getCookie")
    public String getCookie(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    model.addAttribute("username", cookie.getValue());
                    break;
                }
            }
        }
        return "displayCookie";
    }
}

 

2. Thymeleaf 템플릿에서 쿠키 사용:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Cookie Example</title>
</head>
<body>
    <h1>Cookie Example</h1>
    <p th:text="'Username: ' + ${username}">Username</p>
</body>
</html>

세션(Session)

세션은 서버 측에 저장되는 사용자 상태 정보를 유지하기 위한 방법이다. 각 사용자는 고유한 세션 ID를 가지고 있으며, 이 세션 ID는 클라이언트의 쿠키에 저장되거나 URL 파라미터로 전달된다.

 

세션의 특징:

  • 서버 측에 저장됨
  • 용량 제한이 없음 (메모리 제한에 따라 다름)
  • 서버에 의해 만료 시간이 관리됨

세션 설정 예제:

 

1. 컨트롤러에서 세션 설정: 

package org.example.springmvc.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class VisitController {
    //HttpSession을 이용한 예시
    //@SessionAttributes을 사용하는 것보다 직관적이고 간단하다.
    @GetMapping("/visit2")
    public String trackVisit(HttpSession session, Model model) {
        // 세션에서 방문 횟수 가져오기
        Integer visitCount = (Integer) session.getAttribute("visitCount");
        if (visitCount == null) {
            visitCount = 0; // 처음 방문 시
        }
        visitCount++; // 방문 횟수 증가
        session.setAttribute("visitCount", visitCount); // 세션에 저장
//        model.addAttribute("visitCount", visitCount);
        return "visit2";
    }

    @GetMapping("resetVisit")
    public String resetVisit(HttpSession session){
        //세션 객체에서 해당 속성만 삭제
        session.removeAttribute("visitCount");
        return "redirect:/visit2";
    }
}

 

- 위에 코드에서는 HttpSession을 사용하여 작성하였다.

- 아래와 같이 @SessionAttributes를 사용하여 세션(Session)을 저장할 수도 있다.

package org.example.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("visitCount") // visitCount2는 세션에 저장할거라고 선언한 것이다
public class SessionController {
    @ModelAttribute("visitCount")
    public Integer initVisitCount2(){
        return 0;
    }

    @GetMapping("/visit2")
    public String trackVisit(@ModelAttribute("visitCount") Integer visitCount2, //세션에서 찾아서 값을 준다!
                             Model model){
        visitCount2++;
        model.addAttribute("visitCount", visitCount2);
        return "visit2";
    }

    @GetMapping("resetVisit")
    public String resetVisit(SessionStatus status){
        status.setComplete();
        return "redirect:/visit2";
    }
}

 

2. Thymeleaf 템플릿에서 세션 사용:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Visit Counter</title>
</head>
<body>
<h1>세션을 이용한 방문 횟수</h1>
<p>
    당신은 <span th:text="${session.visitCount}"></span> 번째 방문입니다..
</p>

<a th:href="@{/resetVisit}">방문 횟수 초기화</a>
</body>
</html>

 

쿠키와 세션의 차이점

  • 저장 위치: 쿠키는 클라이언트 측에, 세션은 서버 측에 저장된다.
  • 보안: 세션이 더 안전하다. 쿠키는 클라이언트에 저장되므로 변조될 위험이 있다.
  • 용량 제한: 쿠키는 용량 제한이 있지만, 세션은 서버 메모리에 의해 제한된다.
  • 만료 시간: 쿠키는 클라이언트가 설정한 만료 시간에 따라 삭제되지만, 세션은 서버에서 설정된 시간에 따라 만료된다.
특징 쿠키(Cookie) 세션(Session)
저장 위치 클라이언트 측 (브라우저) 서버 측
만료 시간 설정 가능 (지속성 쿠키) 서버 설정에 따름 (기본 30분 등)
데이터 크기 제한적 (4KB) 제한 없음 (서버 자원에 따라 다름)
보안성 낮음 (클라이언트 접근 가능) 높음 (서버 측 저장)
사용 예시 자동 로그인, 사용자 선호 설정 로그인 상태 유지, 사용자별 데이터 저장

 

결론

쿠키와 세션은 각각의 장단점이 있으며, 웹 애플리케이션에서 사용자 상태를 유지하는 데 중요한 역할을 한다. 쿠키는 간단한 데이터 저장에 적합하고, 세션은 보안이 중요한 데이터에 적합하다. 스프링에서는 쿠키와 세션을 쉽게 관리할 수 있으며, Thymeleaf를 사용하여 데이터를 간편하게 표시할 수 있다. 적절한 상황에 맞게 쿠키와 세션을 선택하여 사용하면 된다.