Spring boot 学习八 Springboot的filter
一: 传统的javaEE增加Filter是在web.xml中配置,如以下代码:
<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>
二: springBoot中的老方法:
2.1 創建自定义filter
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() { } }
2.2 配置类中增加增加一个@bean
@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, 每个filter对应一个FilterRegistrationBean ,对filter进行排序
@Bean public FilterRegistrationBean otherFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(otherFilter()); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("filterDemo4"); registration.setOrder(2); return registration; }
三 springBoot中的老方法:
3.1 自定义filter
@Order(1) //fitler顺序 //重点 @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() { } }
我们在spring-boot的入口处加上如下注解@ServletComponentScan:
@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(); } }
四: WebStatFilter用于采集web-jdbc关联监控的数据