import java.io.IOException; import java.util.regex.Pattern;
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.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class HeaderFilter implements Filter {
/** * 忽略的URL的正则表达式. */ private static final String IGNORE = "^.+\\.(jsp|png|gif|jpg|js|css|jspx|jpeg|swf|ico)$";
/** * 忽略的URL的正则对象. */ private Pattern ignorePtn;
@Override public void destroy() { }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 解决IE下,IFRAME引起的内部cookie丢失 HttpServletResponse res = (HttpServletResponse) response; res.setHeader("P3P", "CP=CAO PSA OUR");
// 判断URL是否跳过后续的Filter HttpServletRequest req = (HttpServletRequest) request;
// URI是“/UserManage/special/pic/201308.jpg”,要把/UserManage去掉。 String path = req.getRequestURI().substring( req.getContextPath().length()); if (ignorePtn.matcher(path).find()) { request.getRequestDispatcher(path).forward(request, response); } else if (chain != null) { chain.doFilter(request, response); } }
@Override public void init(FilterConfig conf) throws ServletException {
// 取得参数 String ignore = conf.getInitParameter("ignore"); if (ignore == null || ignore.trim().length() == 0) { ignore = IGNORE; } else { ignore = ignore.trim(); }
// 创建正则对象 ignorePtn = Pattern.compile(ignore, Pattern.CASE_INSENSITIVE); }
}
|