rahul shalgar
rahul shalgar

Reputation: 1358

Spring boot: How to set & read cookie

I am trying to set the cookie in the response after login & I want to read that cookie on every further rest api calls.. I tried the code like below but I am not getting the cookie value.. please help me.. thanks in advance..

@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "text/plain")
public String setCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
   response.addCookie(new Cookie("token", generateToken()));        
   return "login success";  
}

@RequestMapping(value = "/getResource", method = RequestMethod.POST, consumes = "text/plain")
public String getCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        Arrays.stream(cookies)
              .forEach(c -> System.out.println(c.getName() + "=" + c.getValue()));
    }   
    return "resource list";
}

Upvotes: 0

Views: 8884

Answers (1)

FishingIsLife
FishingIsLife

Reputation: 2362

Set cookie:

Cookie cookie= new Cookie("userName", authentication.getName());
        response.addCookie(cookie);

Use Cookie Value:

public String hello(Model model, HttpServletRequest request, HttpServletResponse response,@CookieValue("userName") String usernameCookie) {
console.log(usernameCookie);
}

hope this helps

Upvotes: 1

Related Questions