Filter,过滤器。动态的拦截请求或者响应,做一些处理

  • 拦截request,处理客户端请求后端时。
  • 拦截response,处理服务端响应客户端之前。

实现Filter的方式:实现Filter接口。

Filter配置方式
1. 在web项目中web.xml进行配置。示例如下:

<filter>
  <filter-name>过滤器类名称</filter-name>
  <filter-class>过滤器实现类的全限定名</filter-class>
  <init-param>
    <param-name>initParam</param-name>
    <param-value>初始参数结果</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>过滤器类名称</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

2.基于Servlet 3.0的新特性,注解

@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {
}

拦截器方法

  • init
 public void init(FilterConfig fConfig) throws ServletException
  • doFilter
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // place your code here
    写 处理代码
    // pass the request along the filter chain
    chain.doFilter(request, response);
}
  • destroy
public void destroy()

上述,init方法会随着容器启动,而进行初始化,并且只初始化一次。容器重启或者关闭,执行销毁方法destroy。

posted on 2018-01-10 10:58  菜码农先生  阅读(69)  评论(0编辑  收藏  举报