java过滤器(Filter)、Spring拦截器(Handler)


首先,tomcat容器中有Servlet容器和Spring容器,java过滤器。

  • Filter 是在 Servlet 规范中定义的,是 Servlet 容器支持的;Handler是在 Spring 容器内的,是 Spring 框架支持的

java过滤器(Filter)、Spring拦截器(Handler)

  • 方法的执行时机不一样:Filter是在Handler前执行的

java过滤器(Filter)、Spring拦截器(Handler)

  • 不同的实现
@Component
public class MyFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("Filter 前置");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("Filter 处理中");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

        System.out.println("Filter 后置");
    }
}

Handler

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("Interceptor 前置");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("Interceptor 处理中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("Interceptor 后置");
    }
}

接着将自定义好的拦截器处理类进行注册,并通过addPathPatternsexcludePathPatterns等属性设置需要拦截或需要排除的URL

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
    }
}

参考文章:

servlet容器,web容器,spring容器,springmvc容器的区别_万米高空的博客-CSDN博客_servlet springmvc区别

拦截器和过滤器的区别 – SegmentFault 思否


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280709.html

(0)
上一篇 2022年8月15日
下一篇 2022年8月15日

相关推荐

发表回复

登录后才能评论