什么是过滤器
1. 定义
过滤器是Servlet的高级特性之一,是实现Filter接口的Java类,能够对目标资源的请求和响应进行截取。
2. 工作原理
filter能够在一个请求到达servlet之前预处理用户请求,也可以在离开servlet时处理http响应:在执行servlet之前,
首先执行filter程序,并为之做一些预处理工作;根据程序需要修改请求和响应。在servlet被调用之后截获servlet的执行
3. 生命周期
实例化->初始化->过滤->销毁
4. 基本方法
@WebFilter(filterName = "httpServletRequestWrapperFilter", urlPatterns = {"/*"})
public class HttpServletRequestWrapperFilter implements Filter {
//初始化方法
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init httpServletRequestWrapperFilter success");
}
//过滤操作处理方法
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("filter anyThing!");
}
//销毁方法
@Override
public void destroy() {
System.out.println("destroy httpServletRequestWrapperFilter success");
}
}
5. 和拦截器的区别
1.实现原理不同
1.1: 过滤器的实现基于回调函数
1.2: 拦截器基于Java的反射机制【动态代理】实现
2.执行顺序不同,一个请求进入Tomcat依次是 Tomcat - > Filter -> Servelt -> Interceptor -> controller
2.1: 过滤器是在servlet前后处理请求
2.2: 拦截器是在controller前后处理请求
6. 实现方式
实现filter接口,并注册进web容器中
6.1 springboot 通过注解WebFilter注册,@ServletComponentScan 扫描过滤类
@WebFilter(filterName = "httpServletRequestWrapperFilter", urlPatterns = {"/*"})
public class HttpServletRequestWrapperFilter implements Filter {
......
}
@SpringBootApplication
@ServletComponentScan(basePackages = {"com.demo.springboot.servlet","com.demo.springboot.filter"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
6.2 通过 FilterRegistrationBean 注册过滤类
@Bean
public FilterRegistrationBean wrapperFilterRegisBean() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpServletRequestWrapperFilter());
registration.addUrlPatterns("/*");
registration.setName("httpServletRequestWrapperFilter");
return registration;
}
6.3 通过JAVA Bean 注册过滤类,但是无法配置映射过滤地址
@Component
public class HttpServletRequestWrapperFilter implements Filter {
......
}
6.4 在web. xml中配置过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<!--配置过滤器-->
<filter>
<filter-name>FilterTest</filter-name>
<filter-class>com.yangcq.filter.FilterTest</filter-class>
</filter>
<!--映射过滤器-->
<filter-mapping>
<filter-name>FilterTest</filter-name>
<!--“/*”表示拦截所有的请求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>