拦截器、过滤器理解
1、过滤器
过滤器是在请求进入tomcat容器后,但请求进入servlet之前进行预处理的。请求结束返回也是,是在servlet处理完后,返回给前端之前。
理解上面这句话我们就可以知道,进入servlet之前,主要是两个参数:ServletRequest,ServletResponse 那我们得到这两个测试可以干哪些事呢?
我们可以通过ServletRequest得到HttpServletRequest,此时你就可以对请求或响应(Request、Response)那就可以对对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息、字符集统一等一些高级功能。它主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理。使用Filter的完整流程:Filter对用户请求进行预处理,接着将请求交给Servlet进行处理并生成响应,最后Filter再对服务器响应进行后处理。。它是随你的web应用启动而启动的,只初始化一次,以后就可以拦截相关请求,只有当你的web应用停止或重新部署的时候才销毁。(每次热部署后,都会销毁)。
2、拦截器
从上图我们可以看出过滤器只在servlet前后起作用,所以它既不能捕获异常,获得bean对象等,这些是只能是进入servlet里面的拦截器能过做到。拦截器中用于在某个方法或字段被访问之前,进行拦截然后,在之前或之后加入某些操作。比如日志,安全等。一般拦截器方法都是通过动态代理的方式实现。可以通过它来进行权限验证,或者判断用户是否登陆,或者是像12306 判断当前时间是否是购票时间。
对比一下其实我们可以发现,过滤器能做的事拦截器都能做,二拦截器做的事过滤器不一定做的了。
3、监听器
listener是servlet规范中定义的一种特殊类。用于监听servletContext、HttpSession和servletRequest等域对象的创建和销毁事件。监听域对象的属性发生修改的事件。用于在事件发生前、发生后做一些必要的处理。其主要可用于以下方面:1、统计在线人数和在线用户2、系统启动时加载初始化信息3、统计网站访问量4、记录用户访问路径。
常用的监听器 servletContextListener、httpSessionListener、servletRequestListener)
实现拦截器
通过实现HandlerInterceptor接口方式实现拦截器,同时实现WebMvcConfigurer来注入Bean
public class InterceptorDemo implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
StringBuffer requestURL = httpServletRequest.getRequestURL();
System.out.println("前置拦截器1 preHandle: 请求的uri为:"+requestURL.toString());
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器1 postHandle: ");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("拦截器1 afterCompletion: ");
}
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册第一个拦截器
InterceptorRegistration registration2 = registry.addInterceptor(new InterceptorDemo());
//配置拦截路径
registration2.addPathPatterns("/**");
//配置不拦截的路径
registration2.excludePathPatterns("/**.html");
//注册其他的拦截器,执行顺序和配置顺序有关系
//
// //注册第二个拦截器
// InterceptorRegistration registration = registry.addInterceptor(new InterceptorDemo());
// //配置拦截路径
// registration.addPathPatterns("/**");
// //配置不拦截的路径
// registration.excludePathPatterns("/**.html");
}
}
实现过滤器两种方式
注解方式
监听器上加上@WebFilter,然后启动器上加上@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "filter2")
public class FilterAnnotationTest implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器2开始初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("过滤器2开始工作");
HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse ;
httpResponse.setHeader("yzy","yzy");
System.out.println(httpRequest.getRequestURL());
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("过滤器2销毁");
}
}
@SpringBootApplication
@ServletComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2 注入Bean
通过实现Filter和注入FilterRegistrationBean 实现
public class FilterAnnotationTest implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器2开始初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("过滤器2开始工作");
HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse ;
httpResponse.setHeader("yzy","yzy");
System.out.println(httpRequest.getRequestURL());
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("过滤器2销毁");
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new FilterAnnotationTest ());
registration.addUrlPatterns("/*");
registration.setName("Filter");
registration.setOrder(1);
return registration;
}
}
实现监听器两种方法
1.注解方式
监听器上加上@WebListener,然后启动器上加上@ServletComponentScan
//ServletContextListener 用来检测web服务生命周期
@WebListener
public class WebListenerDemo implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("监听器初始化。。。。。。。。。。。。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("监听器销毁。。。。。。。。。。。");
}
}
@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("。。。创建session成功");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("。。。销毁session");
}
}
@SpringBootApplication
@ServletComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.注入Bean
实现监听器类不再使用@WebListener,而是通过@Configuration和 @Bean进行注入Bean
//ServletContextListener 用来检测web服务生命周期
public class WebListenerDemo implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("监听器初始化。。。。。。。。。。。。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("监听器销毁。。。。。。。。。。。");
}
}
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("。。。创建session成功");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("。。。销毁session");
}
}
@Configuration
public class ListenerConfig {
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean slrBean = new ServletListenerRegistrationBean();
slrBean.setListener(new WebListenerDemo());
return slrBean;
}
@Bean
public ServletListenerRegistrationBean sessionListenerRegistrationBean() {
ServletListenerRegistrationBean slrBean = new ServletListenerRegistrationBean();
slrBean.setListener(new SessionListener());
return slrBean;
}
}
测试
创建controller 同时写入session作用域
@RestController
public class TestController {
@RequestMapping("test")
public String test(HttpServletRequest request){
request.getSession().setAttribute("name","zwq");
//销毁session
request.getSession().invalidate();
return "sussess";
}
}
测试结果