Spring Boot之FilterRegistrationBean-自定义Filter详解

  package com.dbzhang;

  /**

  * @author zdb

  * @description @Configuration和@Bean注解配置使用,就相当于在配置文件中配置bean的注解式用法

  */

  import java.io.IOException;

  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 org.apache.catalina.filters.RemoteIpFilter;

  import org.springframework.boot.web.servlet.FilterRegistrationBean;

  import org.springframework.context.annotation.Bean;

  import org.springframework.context.annotation.Configuration;

  @Configuration

  public class WebConfiguration {

  @Bean

  public RemoteIpFilter remoteIpFilter(){

  return new RemoteIpFilter();

  }

  /***

  * 这个FilterRegistrationBean类可以使用setOrder()方法实现对filter的排序,然后在进行注册

  * https://blog.csdn.net/doctor_who2004/article/details/56055505

  */

  public FilterRegistrationBean testFilterRegistration(){

  FilterRegistrationBean registration = new FilterRegistrationBean();

  registration.setFilter(new MyFilter());

  registration.addUrlPatterns("/*");

  registration.addInitParameter("paramName", "paramValue");

  registration.setName("MyFilter");

  registration.setOrder(1);

  return registration;

  }

  /**

  *

  * @author zdb

  * @description 这个是用来实现Filter

  *

  */

  public class MyFilter implements Filter{

  @Override

  public void destroy() {

  }

  @Override

  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)

  throws IOException, ServletException {

  HttpServletRequest request = (HttpServletRequest)servletRequest;

  System.out.println("this is MyFilter,url:"+request.getRequestURI());

  filterChain.doFilter(servletRequest, servletResponse);

  }

  @Override

  public void init(FilterConfig arg0) throws ServletException {

  }

  }

  }