宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

这篇文章将为大家详细讲解有关Cookie中怎么设置HttpOnly属性,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

利用拦截器实现,判断每次请求的响应是否包含SET-COOKIE头部,重写会话Cookie,添加需要的属性。虽较为生硬,但灵活性强。

新的规范API

新的规范添加SessionCookieConfig接口,用于操作会话Cookie,需要掌握以下主要方法:

setNameString name)
修改Session ID的名称,默认为"JSESSIONID"setDomainString domain)
设置当前Cookie所处于的域
setPathString path)
设置当前Cookie所处于的相对路径
setHttpOnlyboolean httpOnly)
设置是否支持HttpOnly属性
setSecureboolean secure)

若使用HTTPS安全连接,则需要设置其属性为truesetMaxAgeint maxAge)设置存活时间,单位为秒如何使用呢,很方便,在ServletContextListener监听器初始化方法中进行设定即可;下面实例演示如何修改"JSESSIONID",以及添加支持HttpOnly支持:

全局设置Session-Cookie相交互部分属性@WebListenerpublic class SessionCookieInitialization implements ServletContextListener {private static final Log log = LogFactory
   .getLogSessionCookieInitialization.class);public void contextInitializedServletContextEvent sce) {
  log.info"now init the Session Cookie");
  ServletContext servletContext = sce.getServletContext);
  SessionCookieConfig sessionCookie = servletContext
    .getSessionCookieConfig);
  sessionCookie.setName"YONGBOYID");
  sessionCookie.setPathservletContext.getContextPath));
  sessionCookie.setHttpOnlytrue);
  sessionCookie.setSecurefalse);
  log.info"name : " + sessionCookie.getName) + "\n" + "domain:"
    + sessionCookie.getDomain) + "\npath:"
    + sessionCookie.getPath) + "\nage:"
    + sessionCookie.getMaxAge));
  log.info"isHttpOnly : " + sessionCookie.isHttpOnly));
  log.info"isSecure : " + sessionCookie.isSecure));
}public void contextDestroyedServletContextEvent sce) {
  log.info"the context is destroyed !");
}

}需要通过ServletContext对象获得SessionCookieConfig对象,才能够进一步自定义session cookie的属性。

无论以前的硬编码还是新的API实现,目标都是一致的,所产生头部信息也是完全一致。

毫无疑问,后者更为方便快捷,省缺了显示的操作响应元数据。

对当前站点的第一次请求,很容易从响应头信息中看到Set-Cookie的属性值:

不同浏览器平台上测试

在Safari、IE8、Opera 11 一切都很正常

Firefox 3.6、Chrome 9.0,JSESSIONID会继续存在:

YONGBOYID=601A6C82D535343163B175A4FD5376EA; JSESSIONID=AA78738AB1EAD1F9C649F705E

在所有浏览器中,SESSION ID等于新设置的YONGBOYID值(若不相等,问题就严重了!)

在客户端JS无法获得正确的SESSIONI ID了。

Tomcat服务器内置支持

可以不用如上显示设置Cookie domain、name、HttpOnly支持,在conf/context.xml文件中配置即可:

<Context useHttpOnly="true", sessionCookieName="YONGBOYID", sessionCookieDomain="/servlet3" … >...</Context>

既然JAVA应用服务器本身支持会话Cookie设定,那就没有必要在程序代码中再次进行编码了。这是一个好的实践:不要重复造轮子。

这里给出一段测试Session重写的一段脚本:

<div style="margin: 40px; paddding: 10px"><div><a href="sessionCookieTest">正常连接</a></div><div><a href="<%=response.encodeURL"sessionCookieTest") %>">重定向连接</a></div></div>