Cookies added to the HttpServletResponse during an $.ajax POST call do not appear in the response header (there is no set-cookie). The same code does function properly during GET requests.
I have the following code in an interceptor 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"));
}
I'm seeing this issue when returning from a request to this mapping:
@RequestMapping(value = "/api/user/wait", method = RequestMethod.POST)
@ResponseBody
public User waitingApi(HttpSession session) {
Ajax call parameters:
var ajaxMessage = {
url : '/api/user/wait',
type : 'POST',
success : waitCallback,
error : waitErrorCallback
};
On a GET I see the following in my logs:
Cookie json is: { my valid json object }
Header names: [Set-Cookie]
Set-cookie header(s): [user="{ my valid json object }"; Version=1; Path=/]
On a POST I see the following in my logs:
Cookie json is: { my valid json object }
Header names: [Content-Type, Transfer-Encoding, Date, Server]
Set-cookie header(s): [] <--- this is empty, not redacted
After much time spent with google, I found this post: http://mjremijan.blogspot.ca/2012/06/spring-not-setting-cookie-on-ajax.html
Is short, the postHandle interceptor doesn't do anything when the request hits an operation which has the annotation @ResponseBody. You can set the cookie inside the operation method by adding the response object to the operation parameters and calling addCookie inside the operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With