반응형

springboot 에서 cookie와 session 을 어떻게 사용하는지에 대해서 간단한 code를 통해 알아보자.

 

cookie의 추가

.....

@GetMapping("/tmp")
public String tmp(HttpServletRequest req, HttpServletResponse res)
{
  ....
  Cookie newCookie = new Cookie("cname", "cval");
  newCookie.setMaxAge(60); //60 seconds
  newCookie.setSecure(true);
  res.addCookie(newCookie);
  ......
  return "somthing";
}

 사용법은 단순하게 Cookie 생성 후 해당 Cookie의 각 속성에 대해서 지정한 후 response에 포함시켜 전달하면 된다.

 

cookie 내용 확인

....

@GetMapping("/tmp")
public String tmp(@CookieValue String email, @CookieValue("username") String username)
{
 //해당 Annotation 을 통해 접근 가능.
  return "something";
}

@GetMapping("tmp2")
public String tmp2(HttpServletRequest request)
{
 ....
 var cookies = request.getCookies();
 for(var coookie : cookies)
 {
   var cname= cookie.getName();
   var cval = cookie.getValue();
   // do something
 }
 return "something";
}

spring boot 에서는 위처럼 Annotation을 활용하거나 request에 직접 접근하여 cookie를 확인하는 방법이 존재한다.

 

 

session에 접근하기

.....

@GetMapping("tmp")
public String tmp(HttpServletRequest request)
{
 ....
 HttpSession session = request.getSession();
 //session에 특정 정보 추가하기
 session.addAttribute("someKey", "thisValue");
 ........
 
 return "something";
}


@GetMapping("tmp2")
public String tmp2(HttpServletRequest request)
{

  ......
  var session = request.getSession(false);
  //false인 경우 해당 요청에 session 이 존재하지 않을때 null을 반환
  if(session == null)
  {
    session = request.getSession(true);
    //true인 경우 session 이 없으면 새로운 session 을 생성& 반환.
  }
  return "smoethig";
}

@GetMapping("tmp3")
public String tmp3(@SessionAttribute(name="someKey", required=false) String thisValue)
{
  //session에 someKey에 대한 정보가 없는 경우 thisValue는 null
  
}

 

springboot에서는 위처럼 간단하게 session 정보에 대해서 접근 및 가공이 가능하다.

반응형

'SpringBoot' 카테고리의 다른 글

Spring에서의 IOC  (0) 2023.12.11
IOC란 무엇인가?  (0) 2023.12.11
Bean과 Component  (0) 2023.11.30
SpringBoot와 SpringMVC의 차이와 특성에 대하여  (0) 2023.11.29
@SpriongBootApplication 에 대해서  (0) 2023.11.29
Posted by Sweetmeats_boy

블로그 이미지
Sweetmeats_boy

태그목록

Yesterday
Today
Total

달력

 « |  » 2025.2
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

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함