SpringMVC-Filter&Interceptor

SpringMVC的Filter和Interceptor

Filter和Interceptor的执行顺序

1. Filter.init()

2. Filter.doFilter()之前

3. HandlerInterceptor.preHandle()

4. Controller方法执行

5. HandlerInterceptor.postHandle()

6. DispatcherServlet视图渲染

7. HandlerInterceptor.afterCompletion()

8. Filter.doFilter()之后

9. Filter.destroy()

 

Filter和Interceptor的区别

1. Filter是基于函数回调(doFilter()方法)的,而Interceptor则是基于Java反射的(AOP思想)。

2. Filter依赖于Servlet容器,而Interceptor不依赖于Servlet容器。

3. Filter对几乎所有的请求起作用,而Interceptor只能对action请求起作用。

4. Interceptor可以访问Action的上下文,值栈里的对象,而Filter不能。

5. 在action的生命周期里,Interceptor可以被多次调用,Servlet容器在实例化Filter后只调用一次Filter.init()

The servlet container calls the init method exactly once after instantiating the filter. 

Filter的使用:

@WebFilter(filterName = "filterOne", urlPatterns = {"/*"})
public class FilterOne implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("===========before doFilter");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("===========after doFilter");
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}

给你的配置类(或者启动类)加上
@ServletComponentScan("路径")

或者

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new FilterTwo());
        bean.addUrlPatterns("/*");
        return bean;
    }
}

 Interceptor的使用

public class MyInterceptor implements HandlerInterceptor {

  // 如果拦截器要使用容器里的bean的话,要先把拦截器注入到容器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("preHandle"); if (...) {
      return true;
}
return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion"); } }
@Configuration
public class WebConfig implements WebMvcConfigurer {

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

}
posted @ 2019-07-25 21:55  KuroNJQ  阅读(815)  评论(0编辑  收藏  举报