SpringBoot Filter配置

标准SpringMvc filter配置文件如下;

  <filter>
    <filter-name>webContextFilter</filter-name>
    <filter-class>com.x.xx.core.web.WebContextFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>webContextFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

使用SpringBoot时, Filter有如下几种配置方式

方式一: 手动注册

用@Configuration,并注册为Bean
1. 自定义过滤器Filter类
public class filter1 implements Filter {
...
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("this is Filter1");
        filterChain.doFilter(servletRequest, servletResponse);
    }
...
}
2. 注册为Bean
 @Bean
  public FilterRegistrationBean filterRegistrationBeanDemo(){
      FilterRegistrationBean registrationBean = new FilterRegistrationBean();
      registrationBean.setFilter(new filter1());
      registrationBean.addUrlPatterns("/*");
      registrationBean.setName("filter1Name");
      return  registrationBean;
  }

方式二: 注解注册

1. 定义filter类
@WebFilter
public class filterAnnotion implements Filter {
...
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("this is filter filterAnnotion");
    }
..
}
2. 在springboot启动类中添加注解@ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}
阅读更多
换一批

没有更多推荐了,返回首页