[스프링] 쿠키? 세션?

구동현·2024년 1월 25일

스프링

목록 보기
15/21
post-thumbnail

배경지식

  • 우리는 client가 server에게 request를 보내면, server는 client에게 response를 보낸다는 것을 알고 있다.

Cookies

response에 담아서 보내는 cookies


가 아니고,

server가 client에게 보내는 response에 쿠키가 담겨서 보낼 수 있다.

client 가 저장하는 쿠키

client는 response로 받은 쿠키를 저장했다가, 그 도메인에게 다시 request에 넣어서 보낼 수 있다.


public class Cookie  {
    public Cookie(String name, String value) {
        validation.validate(name);
        this.name = name;
        this.value = value;
    }
}
  • cmd + 클릭으로 cookie 클래스를 가볼 수 있다.
  • name - value 형식을 갖는다. (Map처럼?)
public static final String AUTHORIZATION_HEADER = "Authorization";
  • 이름이 바뀌어도 상관없
Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Name-Value
cookie.setPath("/");
cookie.setMaxAge(30 * 60);

HttpServletResponse res

  • 솔직히 이건 잘 모르겠다.
// Response 객체에 Cookie 추가
res.addCookie(cookie);
  • 만든 쿠키를 res에 넣어버린다...!

    public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
    }
  • AUTHORIZATION_HEADER = "Authorization";
  • Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Name-Value
  • cookie 의 이름을 통해 value값을 가져온다!!!

Session

세션 생성하기

    @GetMapping("/create-session")
    public String createSession(HttpServletRequest req) {
        // 세션이 존재할 경우 세션 반환, 없을 경우 새로운 세션을 생성한 후 반환
        HttpSession session = req.getSession(true);

        // 세션에 저장될 정보 Name - Value 를 추가합니다.
        session.setAttribute(AUTHORIZATION_HEADER, "donkuSession Auth");

        return "createSession";
    }

세션 받아오기

    @GetMapping("/get-session")
    public String getSession(HttpServletRequest req) {
        // 세션이 존재할 경우 세션 반환, 없을 경우 null 반환
        HttpSession session = req.getSession(false);

        String value = (String) session.getAttribute(AUTHORIZATION_HEADER); // 가져온 세션에 저장된 Value 를 Name 을 사용하여 가져옵니다.
        System.out.println("value = " + value);

        return "getSession : " + value;
    }

  • 정상적으로 작동한다!!
profile
개발합시다

0개의 댓글