Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 235
M. Hryszczyk Avatar asked Dec 30 '25 10:12

M. Hryszczyk


1 Answers

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";
}
like image 161
Arun P Johny Avatar answered Jan 02 '26 02:01

Arun P Johny