Filter过滤器

一、实现Filter接口(springboot继承OncePerRequestFilter接口也可以)

二、生效配置

方式一

 自定义Filer方法:@WebFilter(filterName = "MyFilter",urlPatterns = "/*.do") 

 Application启动类:@ServletComponentScan

@WebFilter(filterName = "DabaiLoginFilter", urlPatterns = {"/*"})
public class DabaiLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       
    }

    @Override
    public void destroy() {
    }
}

  

方式二

MyFilter类需要实现Filter接口。

<filter>
  <filter-name>MyFilter</filter-name>
  <filter-class>FilterPackage.MyFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>MyFilter</filter-name>
  <url-pattern>/MyServlet</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>ERROR</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

方式三
使用FilterRegistrationBean
在Spring框架中,特别是Spring Boot应用中,你可以使用FilterRegistrationBean来注册过滤器。这种方式允许你通过Java配置来完全控制过滤器的注册和配置。
MyServletFilter类需要实现Filter接口。

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<MyServletFilter> myFilterRegistration() {
        FilterRegistrationBean<MyServletFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new MyServletFilter());
        registration.addUrlPatterns("/filtered/*");
        registration.setName("myFilter");
        registration.setOrder(1); // 设置过滤器链中的顺序
        return registration;
    }
}

posted @ 2022-03-09 13:26  #庄生晓梦  阅读(39)  评论(0编辑  收藏  举报