Cookie设置HttpOnly,Secure,Expire属性

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

http://stackoverflow.com/questions/3985916/dynamic-web-module-option-in-eclipse

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:

Cookie设置HttpOnly,Secure,Expire属性_第1张图片 Cookie设置HttpOnly,Secure,Expire属性_第2张图片

Chrome:

Cookie设置HttpOnly,Secure,Expire属性_第3张图片

IE:

Cookie设置HttpOnly,Secure,Expire属性_第4张图片

 

你可能感兴趣的:(Network,/,Network,Security)