<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>
然而spring-boot中很明顯不能這樣實現,那怎麼辦呢?看完下面的教程,答案天然知道了。java
package com.cppba.filter; import javax.servlet.*; import java.io.IOException; 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 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; }
你會看到控制檯打印以下代碼:git
https://github.com/bigbeef/cppba-spring-bootgithub
最後咱們訪問如下http://127.0.0.1:8080/test
若是你看到控制檯打印出:TestFilterweb
https://github.com/bigbeef/cppba-spring-boot
恭喜你,配置成功!spring
首先定義一個Filterapp
@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() { } }
比較核心的代碼是自定義類上面加上@WebFilter,其中@Order註解表示執行過濾順序,值越小,越先執行ide
咱們在spring-boot的入口處加上以下註解@ServletComponentScan:spring-boot
@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(); } }
這種方法效果和上面版本同樣,可是用起來更加方便!url