Filter的主要用处:
在HttpServletRequest到达Servlet之前,拦截客户的请求,可以修改请求的头和数据
在HttpServletResponse到达客户端之前,拦截响应,可以修改响应的头和数据
Filter的种类
用户授权的Filter:Filter负责检查用户的请求,过滤非法的请求
日志Filter:详细记录某些用户的请求
负责解码的Filter:对非标准的请求进行解码
能改变XML内容的XSLT Filter
@WebFilter(filterName = "/LogFilter", urlPatterns = { "/*" }) public class LogFilter implements Filter { private FilterConfig config; /** * Default constructor. */ public LogFilter() {} /** * @see Filter#destroy() */ public void destroy() { this.config = null; } /** */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.currentTimeMillis(); System.out.println("beginning..."); HttpServletRequest httpRequest = (HttpServletRequest) request; System.out.println("Servlet path :" + httpRequest.getServletPath()); // pass the request along the filter chain chain.doFilter(request, response); System.out.println("end."); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { this.config = fConfig; } }
使用URLRewrite实现网站伪静态