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

2022/8/16 1:22:54

本文主要是介绍java过滤器(Filter)、Spring拦截器(Handler),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

  • Filter 是在 Servlet 规范中定义的,是 Servlet 容器支持的;Handler是在 Spring 容器内的,是 Spring 框架支持的
  • 方法的执行时机不一样:Filter是在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 思否





这篇关于java过滤器(Filter)、Spring拦截器(Handler)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程