Issue
I need to set a cookie with redirect in my login controller. I used code below to set cookie.
@RequestMapping("/fbresponse")
public String getToken(@RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
In my index I try to retrive the cookie using following code:
@RequestMapping("/")
public String getIndex(@CookieValue(value="logged", required=false)String test){
user.setLastPage("/");
loginCheck();
System.out.println(test);
return "index";
}
But it always returns null. I tried returning new ModelAndView. It also did not work and since I need some components in model it does not suit my requirement. How can set and retrieve a cookie? Is it possible to do it with redirect?
UPDATE I have class level @RequestMapping in my login controller.
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/fbresponse")
public String getToken(@RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
}
When I remove the class level request mapping add cookies works. How can I add a cookie correctly with class level request mapping?
Solution
You need to set the path of the cookie, otherwise it's valid only for the current path.
Answered By - JB Nizet