zoukankan      html  css  js  c++  java
  • Filter过滤器和Interceptor过滤器

    Filter过滤器

      过滤器Filter依赖于servlet容器,基于函数回调,他几乎可以对所有的请求进行过滤,过滤器只能在容器初始化的时候调用一次

    Inerceptor拦截器

      拦截器Inerceptor依赖于web框架,在SpringMVC中就依赖于SrpingMVC,在实现上基于java的反射机制实现,属于面向切面编程的一种运用。

    由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入进行一些业务操作。同时一个拦截器实例在一个Controller生命周期内可以多次调用,缺点就是拦截器只能对Controller请求进行拦截,对其他的一些访问比如静态资源访问的请求则没有办法进行拦截处理

    Filter过滤器实现

    @Configuration
    public class TestFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("在DispatcherServlet之前执行");
            filterChain.doFilter(servletRequest,servletResponse);
            System.out.println("在返回给客户端之前执行,但是在Interceptor拦截器之后执行");
        }
    }

    fileterChain.doFilter()方法的作用:

      filter过滤器是以链表的形式进行调用的,配置了几个就有几个,一个个串联在一起,doFilter方法中的filterChain,doFilter方法的作用就是将请求转发给过滤器链表中的下一个过滤器如果没有下一个过滤器就会回到原本的过滤器如果不加filterChain,doFilter()方法就不会向下执行了。

    Interceptor拦截器代码实现

    @Component
    public class Interceptor1 implements HandlerInterceptor {
    
        public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
            System.out.println("1************在DispatcherServlet之前执行**********");
            return true;
        }
    
        public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
            System.out.println("1************在controller执行之后的DispatcherServlet之后执行**********");
        }
    
        public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
            System.out.println("1************在页面渲染完成返回给客户端之前执行**********");
        }
    }
    //配置拦截
    @Component
    public class WebMvcConfig implements WebMvcConfigurer { @Autowired private Interceptor1 interceptor1; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor1).addPathPatterns("/*"); } }
  • 相关阅读:
    【一些思路】web和app测试的区别
    【Python】I/O和比赛的其他一些问题
    【Python】迭代器和生成器的个人理解,再讲一讲协程
    【TCP/IP】如果打不开一个网页,需要如何处理?
    DOM事件
    GASP动画的基本使用
    Velocity的使用方法
    Swiper和Swiper Animate使用方法
    DOM操作
    JavaScript函数
  • 原文地址:https://www.cnblogs.com/HQ0422/p/14272876.html
Copyright © 2011-2022 走看看