Is there any way to add cookie in method with @ResponseBody annotation?

 

Questions


I build my web application based on Spring MVC and come across a problem whilst trying to add a cookie in a method handling an ajax request.

I realized that method with @ResponseBody (in my example it returns a string value) does not create a “real” response and added cookies are lost.

Is there any way to add a cookie in a method called via ajax (and therefore annotated with @ResponseBody) in Spring MVC?

 

 

————————————————-

Answer

You can use the following signature to do this

@ResponseBody
public String x((HttpServletRequest request, HttpServletResponse response){
    Cookie userCookie = new Cookie("<name>", "<valie>");
    //set other cookie properties
    response.addCookie(userCookie);

    return "xxx";
}

ajax,annotations,cookies,spring-mvc,web-applications

Facebook Comments

Post a comment