程序员SpringBoot极简教程 · Spring Boot

Spring Boot:自定义filter

2017-12-28  本文已影响572人  聪明的奇瑞

前言

<filter>
     <filter-name>TestFilter</filter-name>
        <filter-class>com.cppba.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>TestFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <init-param>
       <param-name>paramName</param-name>
       <param-value>paramValue</param-value>
    </init-param>
</filter-mapping>

方法一

创建自定义 Filter

public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    System.out.println("TestFilter");
}

@Override
public void destroy() {

}
}

通过 @Bean 将过滤器注入到 IOC 容器中,并通过 setOrder 方法设置过滤器位置(过滤器链中的位置)

@Bean
public FilterRegistrationBean testFilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new TestFilter());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName", "paramValue");
    registration.setName("testFilter");
    registration.setOrder(1);
    return registration;
}

方法二

创建自定义 Filter 并添加 Servlet3 的 @WebFilter 注解,@Order 为过滤器链中的位置

@Order(1)
//重点
@WebFilter(filterName = "testFilter1", urlPatterns = "/*")
public class TestFilterFirst implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("TestFilter1");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

在启动类上添加扫描

@SpringBootApplication(scanBasePackages = "com.cppba")
//重点
@ServletComponentScan
public class Application {
    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        Environment environment = app.run(args).getEnvironment();
    }
}
上一篇下一篇

猜你喜欢

热点阅读