版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yzy199391/article/details/85377048
问题描述
最近开发遇到一个问题,在用HttpServletResponse的sendRedirect方法做重定向时,创建Cookie并添加到response中,重定向后,在chrome浏览器通过开发者工具无法查看到添加到cookie内容。
重定向代码如下:
try {
Cookie xReferCookie = new Cookie("x-referer", xReferer + "_" + token);
Cookie xChannelCookie = new Cookie("x-channel", xChannel);
xReferCookie.setPath("/");
xChannelCookie.setPath("/");
xReferCookie.setDomain("xxxx.com");
xChannelCookie.setDomain("xxxx.com");
response.addCookie(xReferCookie);
response.addCookie(xChannelCookie);
response.sendRedirect(targetUrl);
} catch (IOException e) {
log.error("跳转目标h5页面失败,targetUrl: []", targetUrl);
return new ResponseEntity("error", HttpStatus.INTERNAL_SERVER_ERROR);
}
#Cookie类型、创建方式及特性
注: Cookie的MaxAge单位为秒。
内存Cookie:
由浏览器维护,保存在内存中,浏览器关闭后就消失了,其存在时间是短暂的。
硬盘Cookie:
保存在硬盘里,有一个过期时间,除非用户手工清理或到了过期时间,硬盘Cookie不会被删除,其存在时间是长期的
MaxAge: 该Cookie失效的时间,单位秒。如果为正数,则该Cookie在maxAge秒之后失效。如果为负数,该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。如果为0,表示删除该Cookie。默认为–1
由上述可知,上面我的代码中未通过setMaxAge()
方法设置有效时间,其值默认为-1,即此时创建的cookie为临时cookie,只存在在浏览器进程中,当浏览器关闭,进程失效。
参考地址: