cookie 设置 httpOnly属性防止js读取cookie.
建立filter拦截器类
CookieHttpOnlyFilter
import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * *CookieにHTTPOnly属性を設定インターセプタークラス.
** @author hnnc* @author $Author$* @version $Id$ */public class CookieHttpOnlyFilter implements Filter { /** {@inheritDoc} **/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; Cookie[] cookies = httpReq.getCookies(); if (cookies != null) { Cookie cookie = cookies[0]; if (cookie != null) { HttpSession session = httpReq.getSession(); if (session != null) { String sessionId = session.getId(); // httpの设置 httpResp.addHeader("Set-Cookie", "JSESSIONID=" + sessionId + "; Path=/admin; HttpOnly"); // httpsの设置// httpResp.addHeader("Set-Cookie", "JSESSIONID=" + sessionId// + "; Path=/admin;Secure; HttpOnly"); } } } chain.doFilter(httpReq, httpResp); } /** {@inheritDoc} **/ public void destroy() { } /** {@inheritDoc} **/ public void init(FilterConfig filterConfig) throws ServletException { }}
web.xml中配置拦截器
CookieHttpOnly jp.co.univ.www.admin.filter.CookieHttpOnlyFilter CookieHttpOnly /*
参考: