java cookie secure_Cookie设置HttpOnly,Secure,Expire属性

标签:

在eclipese中创建Web工程时,有个dynamic web module version选项,首先解释下这个选项的意思:

That version correlates with Servlet API version. Servlet 3.0 (released at december 2009 as part of Java EE 6) runs on Servlet 3.0 containers only (Tomcat 7, Glassfish 3, JBoss AS 6, etc).Servlet 2.5 (released at 11 may 2006 as part of Java EE 5) runs on Servlet 2.5 containers only or newer (Tomcat 6, Glassfish 2, JBoss AS 5, etc). Servlet 2.4 (released at november 2003 as part of J2EE 1.4) runs on Servlet 2.4 containers only or newer, etcetera.

You just need to pick the right API version whatever you want to implement your webapp in. Or if you don‘t have the freedom in picking the servlet container used, then pick the API which suits the servlet container version the best.

As to why the JDK defaults to one or other, it‘s just the minimum JDK requirement of the Servlet API version in question. Often, when you‘re picking an older Servlet API, in reality the JRE/JDK used is also that old.

Tomcat版本为6.0.39,JDK版本为1.6update45

在Web工程上增加一个Filter对Cookie进行处理

public class CookieFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;

HttpServletResponse resp = (HttpServletResponse) response;

Cookie[] cookies = req.getCookies();

if (cookies != null) {

Cookie cookie = cookies[0];

if (cookie != null) {

/*cookie.setMaxAge(3600);

cookie.setSecure(true);

resp.addCookie(cookie);*/

//Servlet 2.5不支持在Cookie上直接设置HttpOnly属性

String value = cookie.getValue();

StringBuilder builder = new StringBuilder();

builder.append("JSESSIONID=" + value + "; ");

builder.append("Secure; ");

builder.append("HttpOnly; ");

Calendar cal = Calendar.getInstance();

cal.add(Calendar.HOUR, 1);

Date date = cal.getTime();

Locale locale = Locale.CHINA;

SimpleDateFormat sdf =

new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",locale);

builder.append("Expires=" + sdf.format(date));

resp.setHeader("Set-Cookie", builder.toString());

}

}

chain.doFilter(req, resp);

}

public void destroy() {

}

public void init(FilterConfig arg0) throws ServletException {

}

}

web.xml:

cookieFilter

com.sean.CookieFilter

cookieFilter

/*

FireFox:

ddfd977016623529cf60c2a413abfa98.png

a442e6f111343057fdb6aee56dccf222.png

Chrome:

fb5d6f9e8d8ebb5338a431afdc488df0.png

IE:

7837ca9d4a53ebda37e1f652a631132a.png

版权声明:本文为博主原创文章,未经博主允许不得转载。

标签:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值