过滤器简介
- 过滤器依赖Servlet容器,属于Servlet规范的一部分。
- 在实现上基于Servlet容器的函数回调,可以对几乎所有请求进行过滤。
- Filter的生命周期由Servlet容器管理。
过滤器执行流程
过滤器配置使用方式一
@Order(1) // 指定过滤器的执行顺序
@WebFilter(filterName = "CostTimeFilter", urlPatterns = "/*" , initParams = {
@WebInitParam(name = "URL", value = "http://localhost:8080")})
public class CostTimeFilter implements Filter {
private String url;
/**
* filter对象只会创建一次,init方法也只会执行一次。
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.url = filterConfig.getInitParameter("URL");
System.out.println("Filter init...");
}
/**
* 主要的业务代码编写方法
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
System.out.println(start + " Filter doFilter before...");
filterChain.doFilter(servletRequest, servletResponse);
long end = System.currentTimeMillis();
System.out.println(end + "Filter doFilter after...");
}
/**
* 在销毁Filter时自动调用。
*/
@Override
public void destroy() {
System.out.println("Filter destroy...");
}
}
@RestController
public class IndexContoller {
@RequestMapping("/query")
public void query() throws Exception {
System.out.println("IndexContoller query...");
}
}
@SpringBootApplication
@ServletComponentScan // 扫描 Servlet 相关的组件
public class SpringBootFilterApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootFilterApplication.class, args);
}
}
过滤器配置方式二
public class CostTimeFilter implements Filter {
private String url;
/**
* filter对象只会创建一次,init方法也只会执行一次。
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.url = filterConfig.getInitParameter("URL");
System.out.println("Filter init...");
}
/**
* 主要的业务代码编写方法
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
System.out.println(start + " Filter doFilter before...");
filterChain.doFilter(servletRequest, servletResponse);
long end = System.currentTimeMillis();
System.out.println(end + "Filter doFilter after...");
}
/**
* 在销毁Filter时自动调用。
*/
@Override
public void destroy() {
System.out.println("Filter destroy...");
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CostTimeFilter());
registration.addUrlPatterns("/*");
registration.setName("CostTimeFilter");
registration.setOrder(1);
return registration;
}
}