Filter过滤器的应用

Filter过滤器作用:在每次请求服务资源时做过滤处理。

原理:Filter接口中有一个doFilter方法,当开发人员编写好Filter类实现doFilter方法,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前(服务器内部对资源的访问机制决定的),都会先调用一下filter的doFilter方法。

项目应用:系统长时间未操作超时自动断开连接,在filter中判断session是否失效,失效则直接返回首页。

下面的示例代码是设置每次请求后台服务时先设置编码格式为UTF-8

public class EncodingFilter implements Filter {

  private String encoding = null;

  public void destroy() {
    encoding = null;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String encoding = getEncoding();
    if (encoding == null){
      encoding = "UTF-8";
    }
    request.setCharacterEncoding(encoding);// 在请求里设置上指定的编码

    //这里可以做筛选,判断Session中内容是否已过期,如过期则可以在这里直接设置返回登录页面,不继续执行下面的doFilter请求了。

    ...... 
    chain.doFilter(request, response); //请求服务端资源
  } 

  public void init(FilterConfig filterConfig) throws ServletException {
    this.encoding = filterConfig.getInitParameter("encoding");
  }

  private String getEncoding() {
    return this.encoding;
  }
}

web.xml文件中需要配置如下:

<filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>com.logcd.filter.EncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>EncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

通过上面的代码设置实现之后,用户每次请求服务时均会进入doFilter方法先进行过滤

原文地址:https://www.cnblogs.com/onlyperfect/p/8313256.html