A clear view of the operating principle SpringMVC, and interceptors & Filters difference between the execution order

First, a case where FIG clarifying filter and the process in response to the request interceptor SpringMVC

Filter and interception process in the case of a request response SpringMVC

  • Web servers : network interworking procedure for processing requests and responses between a client and a server, the Web server can request and response must conform to the HTTP protocol processing. Bluntly said, requesting data passed by the client to the Web server, Web server, and data response to the client are strings, or that the Web server can only handle static resources. When a client initiates a HTTP request, Web server first checks whether the content requested by the client is static resources. If it is a static resource, Web server directly to static resources back to the client. When content client discovery request is a dynamic content, Web server forwards the request to the Servlet container will be processed. Servlet Container dealt forwards the response to the Web server will be transformed to conform to the HTTP response to the HTTP protocol format.
  • Servlet containers : a Web server to support the servlet extensions part of dynamic interaction between the client and the Web server. Bluntly put, it is the Web server can not understand the HTTP request, understandably given the Servlet container. Then, Servlet container interpreted as the result of the request will be appreciated that the Web server, a Web server in response to requests forwarded to the client.
  • Filter Filter : Filter Filter the same and are based on Java Servlet Web component, managed by the Servlet container, to generate dynamic content. That method is performed, the filter Filter initialization init (), filtering the doFilter (), destroy destroy (), etc. are invoked by the Servlet container. Note that when the Web server is discovered HTTP request dynamic content, forwards the request to the Servlet container. Servlet container had first to find the corresponding Servlet to process, but when there is a matching request Filter and filter, Filter Servlet container will acquire a first filter to process the request again, and then to the Servlet to process. Since the filter is Filter callbacks use, when the filter Filter Servlet dealt Servlet response will continue to be reprocessed. Seen from the FIG., The Servlet container life cycle is longer than earlier & Spring container, so the container Spring Bean is not injected into the filter Filter used. This feature is also generally a direct result Filter mainly used for processing requests and responses, rather than on specific business processes.
  • Interceptor interceptor : interceptor Interceptor is managed by Spring, Spring IOC stored in a container assembly, is an implementation of Spring's Aspect Oriented Programming AOP. Interceptor is based on a dynamic proxy, using reflection to achieve. It Spring IOC and other components in the same life cycle is controlled by the Spring, the interceptor can be injected into the Bean Spring IOC container other business processes. Of course, the interceptor can also realize the full effect Filter filter. So, more powerful interceptor, the interceptor is also recommended.
  • SPRINGMVC : Spring-based web components, dynamic request processing. Its core classes DispatcherServlet, commonly referred to a front end controller. All requests from the client, the request will be forwarded by the DispatcherServlet, from which then returns a response to the Servlet container. Specific operating procedure shown above, will be interpreted by the source below.

Filter and the difference in the interpretation of the interceptor portions already clear

Two, Filter filter for use in the project SpringBoot

Filter filter original arranged Spring projects are configured in web.xml. Without SpringBoot web.xml file in the project, but the new configuration.

1, annotation mode

There are two ways annotation program, as follows:

  • @WebFilter+ @Component 或 @Configuration+ ( @OrderOptional)
@Slf4j
@Order(2)
@Component
@WebFilter(urlPatterns="/*", filterName="filter2")
public class Filter2 implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("{}初始化完成",this.getClass().getName());
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("{}执行过滤开始....",this.getClass().getName());
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("{}执行过滤结束....",this.getClass().getName());
    }

    public void destroy() {
        log.info("{}销毁",this.getClass().getName());
    }
}
  • @WebFilter+ @ServletComponentScan("Filter所在包目录")+ ( @OrderOptional)
@Slf4j
@Order(2)
@WebFilter(urlPatterns="/*", filterName="filter2")
public class Filter2 implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("{}初始化完成",this.getClass().getName());
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("{}执行过滤开始....",this.getClass().getName());
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("{}执行过滤结束....",this.getClass().getName());
    }

    public void destroy() {
        log.info("{}销毁",this.getClass().getName());
    }
}
@ServletComponentScan("com.mapc.j2ee.filter")
@SpringBootApplication
public class J2eeFilterInterceptorServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(J2eeFilterInterceptorServletApplication.class, args);
    }

}

Add SpringBoot inlet class @ServletComponentScanannotation, or adding a custom class FilterConfig @ServletComponentScan+ @Configurationcomposition annotations can.

2, encoding

Use FilterRegistrationBeaninjection.

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean registerFilter1(){
        FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new Filter1());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.setUrlPatterns(Collections.singleton("/*"));
        return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean registerFilter2(){
        FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new Filter2());
        filterRegistrationBean.setOrder(2);
        filterRegistrationBean.setUrlPatterns(Collections.singleton("/*"));
        return filterRegistrationBean;
    }

}

Three, Interceptor interceptor for use in SpringBoot project

1, inheritance WebMvcConfigurationSupport+ @Configuration 或 @Componentnotes

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new Interceptor1()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}
@Slf4j
@Order(2)
public class Interceptor1 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("{}请求处理前拦截",this.getClass().getName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("{}请求处理后返回ModelAndView拦截",this.getClass().getName());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("{}请求处理后返回给前端视图拦截",this.getClass().getName());
    }
}

Four, SpringMVC operating principle source Interpretation

There supplemented on time


References:
[1]: the Java Servlet 3.1 Specification, "the Java Servlet 3.1 specification" Chinese translation and examples
[2]: What is the Servlet container?

Published 35 original articles · won praise 32 · views 90000 +

Guess you like

Origin blog.csdn.net/u012995888/article/details/103398278