Filter(过滤器)

来源:互联网 发布:java中私有属性 编辑:程序博客网 时间:2024/06/05 20:04


一、Filter作用:

  • 1.先于Servlet获取并处理请求数据。
  • 2.后于Servlet获取并处理响应数据

二、Filter种类:

  • 1.日志Filter:请求和响应数据写入日志。
  • 2.编码Filter:对数据进行编解码。
  • 3.用户授权的Filter:检查请求,过滤非法请求。

三、使用Filter两步:

  • 1.Filter类实现;
  • 2.web.xml中注册Filter。

                  

四、过滤器的处理链: 1.过滤器先于Servlet处理请求 ->2.Servlet处理请求和响应 ->3.过滤器后于 Servlet处理响应。


LogFilter(日志过滤器):将请求和响应的信息记录在日志中。

public class LogFilter implements Filter {        private FilterConfig config;// FilterConfig可用于访问Filter的配置信息    // 实现初始化方法    public void init(FilterConfig config) {        this.config = config;    }    // 实现销毁方法    public void destroy() {        this.config = null;    }    // 过滤器处理数据的核心方法    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {
        ServletContext context = this.config.getServletContext();//获取ServletContext对象,用于写日志        long before = System.currentTimeMillis();
//----------1.先于Servlet处理请求---------
System.out.println("过滤开始...");              
context.log("请求地址为: " + ((HttpServletRequest) request).getServletPath());// 请求信息写入日志
        //----------2.继续往下传递request对象和response对象,交给Servlet处理---------        
chain.doFilter(request, response);      
          
//----------3.后于Servlet处理响应---------
        context.log("响应字符编码为:"+response.getCharacterEncoding());// 响应信息写入日志   
        long after = System.currentTimeMillis();             
context.log("过滤结束... 处理时间为: " + (after - before));    }
}

原创粉丝点击