paarandika
paarandika

Reputation: 1439

Setting Cookie not working in Spring web-mvc 4

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?

Upvotes: 4

Views: 9036

Answers (1)

JB Nizet
JB Nizet

Reputation: 692081

You need to set the path of the cookie, otherwise it's valid only for the current path.

Upvotes: 14

Related Questions