在$.ajax POST调用期间添加到HttpServletResponse的Cookie不会出现在响应头中(没有set-cookie).在GET请求期间,相同的代码可以正常运行.
我在拦截器postHandle中有以下代码:
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
.
.
Cookie cookie = new Cookie(User.USER_KEY, userAsJson);
LOGGER.info("Cookie json is: " + userAsJson);
cookie.setPath("/");
response.addCookie(cookie);
LOGGER.info("Header names: " + response.getHeaderNames());
LOGGER.info("Set-cookie header(s): " + response.getHeaders("Set-Cookie"));
}
从请求返回到此映射时,我看到了这个问题:
@RequestMapping(value = "/api/user/wait", method = RequestMethod.POST)
@ResponseBody
public User waitingApi(HttpSession session) {
Ajax调用参数:
var ajaxMessage = {
url : '/api/user/wait',
type : 'POST',
success : waitCallback,
error : waitErrorCallback
};
在GET上,我在日志中看到以下内容:
Cookie json is: { my valid json object }
Header names: [Set-Cookie]
Set-cookie header(s): [user=”{ my valid json object }”; Version=1;
Path=/]
在POST上,我在日志中看到以下内容:
Cookie json is: { my valid json object }
Header names: [Content-Type, Transfer-Encoding, Date, Server]
Set-cookie header(s): [] <— this is empty, not redacted
最佳答案 花了很多时间在谷歌上,我发现这篇文章:
http://mjremijan.blogspot.ca/2012/06/spring-not-setting-cookie-on-ajax.html
简而言之,当请求命中具有注释@ResponseBody的操作时,postHandle拦截器不会执行任何操作.您可以通过将响应对象添加到操作参数并在操作中调用addCookie来在操作方法中设置cookie.