有没有办法在带有@ResponseBody 注释的方法中添加 cookie? [英] Is there any way to add cookie in method with @ResponseBody annotation?

查看:55
本文介绍了有没有办法在带有@ResponseBody 注释的方法中添加 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基于 Spring MVC 构建了我的 Web 应用程序,并在尝试在处理 ajax 请求的方法中添加 cookie 时遇到问题.

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.

我意识到带有@ResponseBody 的方法(在我的示例中它返回一个字符串值)不会创建真实"响应并且添加的 cookie 会丢失.

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.

有没有办法在 Spring MVC 中通过 ajax 调用的方法中添加 cookie(因此用 @ResponseBody 进行注释)?

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

推荐答案

您可以使用以下签名来做到这一点

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";
}

这篇关于有没有办法在带有@ResponseBody 注释的方法中添加 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆