Spring Filter and Intercpetor interceptor

The difference between filters and interceptors

In Spring development, we will encounter the use of Filter and Interceptor. They can do some preprocessing on some requests, but there are still big differences between them:

  1. The interceptor is based on Java's reflection mechanism, and the filter is based on function callbacks.
  2. Filter is defined in the Servlet specification and supported by the Servlet container. The interceptor is in the Spring container and is supported by the Spring framework.
  3. Filter only works before and after Servlet. The interceptor can go deep before and after the method, before and after the exception is thrown, so the use of the interceptor has greater flexibility. Therefore, in the Spring framework program, the interceptor should be used first)
  4. The interceptor can access the objects in the action context and value stack, but the filter cannot.
  5. In the life cycle of the action, the interceptor can be called multiple times, and the filter can only be called once when the container is initialized.

Application scenario

  • Log record: Record the log of requested information for information monitoring, information statistics, PV (Page View) calculation, etc.
  • Permission check: such as login detection, enter the processor to detect whether it is logged in, if not, return to the login page directly;
  • The interceptor can go deep into the execution process before and after the method, and can calculate the execution time of the method to judge the performance problem

filter

Filter interface

public interface Filter {
    default void init(FilterConfig filterConfig) throws ServletException {
    }

    void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;

    default void destroy() {
    }
}

Filter is an interface in javax.servlet, it has a life cycle, there is a process of initialization, execution and destruction.

Implementation of the filter

Let's take a look at a demo of permission verification I wrote


public class AuthCheckFilter implements Filter {


    //@Resource //Not effective
    private UserService userService;
    //The creation and destruction of the Filter is the responsibility of the WEB server. When the web application starts,
    //The web server will create an instance of Filter and call its init method to initialize,
    //The container will only call this method once when the filter is instantiated.
    //The container passes a FilterConfig object for this method, which contains configuration information related to Filter
    public void init(FilterConfig filterConfig) throws ServletException {
       //Get the container context, you can perform operations on Bean
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        userService = (UserServiceImpl)ctx.getBean(UserServiceImpl.class);


    }
    //Every time the filter intercepts it will be executed. It should be noted that an instance of the filter can serve multiple requests at the same time,
    // Especially need to pay attention to thread synchronization, try to avoid or use less instance variables.
    // In the filter's doFilter() method implementation, any place that appears before the FilterChain's doFilter method,
    //request is available; response is available after doFilter() method.
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String user_token = request.getHeader("user_token");
        String methodString=request.getMethod();
        //This judgment is just a simple description, through the init method we can get the bean object for verification operations
        if(!userService.findOne(user_token)){
            response.setContentType("application/json; charset=utf-8");
            String jsonString="{\"status\":\"false\",\"info\":\"User not logged in or timeout\"}";
            OutputStream os = response.getOutputStream();
            os.write(jsonString.getBytes());
            os.close();
        }
        //Here is a simple demo, deal with the specific logic when needed
        if(StringUtils.isEmpty(user_token)){
            response.setContentType("application/json; charset=utf-8");
            String jsonString="{\"status\":\"false\",\"info\":\"User not logged in or timeout\"}";
            OutputStream os = response.getOutputStream();
            os.write(jsonString.getBytes());
            os.close();
        }

        filterChain.doFilter(servletRequest, servletResponse);

    }
    //Called before the Web container unloads the Filter object
    //If the filter uses other resources, these resources need to be released in this method.
    public void destroy() {

    }
}


In the initialization method init() of the above code, I added methods to obtain the Spring context and bean objects, so that we can have more flexibility in processing.

Filter configuration is added in web.xml

 <filter>
    <filter-name>authFilter</filter-name>
    <filter-class>app.filter.AuthCheckFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>authFilter</filter-name>
    <url-pattern>/user/*</url-pattern>
</filter-mapping>
The <!--<filter-mapping> tag is sequential, and its declaration order shows how the container forms the filter chain -->
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Filter demo
https://github.com/lili1990/learning/tree/master/spring-learning/spring-filter

Interceptor

Interceptor interface

public interface HandlerInterceptor {

    //Preprocessing callback method to implement processor preprocessing (such as login check)
    //The third parameter is the response processor, the intercepted controller object
    boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception;

    //Post-processing callback method to implement post-processing of the processor, but before rendering the view
    void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception;


    //Callback method when the entire request is processed, that is, when the view is rendered
    void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception;

}

Intercept adapter

public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {

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

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

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

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

}

This is the adapter of HandlerInterceptor, which simply implements HandlerInterceptor (so the three callback methods here are empty implementations, preHandle returns true.), we do not need to implement all the methods of HandlerInterceptor, we use HandlerInterceptorAdapter to implement the methods we need .

Operation process:

Interceptor

Note: In the abnormal process, such as the process interrupted by HandlerInterceptor2 (preHandle returns false), here only the afterCompletion method where the preHandle of the interceptor before it returns true is called.

Interceptor configuration


    <mvc:annotation-driven />

    <context:component-scan base-package="app.controller"/>

    <context:component-scan base-package="app.service"/>
 <!--Interceptor configuration-->
    <mvc:interceptors>
        <!-- Log interceptor, global interception -->
        <bean class="app.interceptor.LogInterceptor"/>
        <!--Configure interceptors, multiple interceptors, sequential execution -->
        <!--Authority verification, exclude some requests-->
        <mvc:interceptor>
            <!-- matches the URL path, if not configured or /**, all Controllers will be intercepted -->
            <mvc:mapping path="/**"/>
            <!--Exclude part of the request and will not be intercepted (the intercepted requests below are all swagger requests) -->
            <mvc:exclude-mapping path="/swagger-ui.html*"/>
            <mvc:exclude-mapping path="/webjars/**"/>
            <mvc:exclude-mapping path="/configuration/ui/**"/>
            <mvc:exclude-mapping path="/swagger-resources/**"/>
            <mvc:exclude-mapping path="/v2/**"/>
            <bean class="app.interceptor.AuthCheckInterceptor" />
        </mvc:interceptor>
        <!-- When setting multiple interceptors, first call the preHandle method in order, and then call the postHandle and afterCompletion methods of each interceptor in reverse order -->
    </mvc:interceptors>

Interceptor demo
https://github.com/lili1990/learning/tree/master/spring-learning/spring-interceptor

In-depth study of interceptors can be seenSpring DispatcherServlet

Intelligent Recommendation

Filter and interceptor in Spring-Boot

1. Filter In fact, the filter (Filter) is very similar to Servlet, which is a component of Java. That is, before sending to Servlet, you can intercept and process the request, or you can deal with the...

Spring Filter interceptor configuration

Spring Filter interceptor configuration Filter can be regarded as a "enhanced version" of Servlet. It is mainly used to pre -process user requests. It can also be postponed by HTTPSERVLESPON...

Spring -interceptor, filter

1. Interceptor definition: The interceptor is applied to cut -faced programming, that is, call a method before your service or a method, or call a method after the method. It is a reflection mechanism...

Spring--interceptor, character encoding filter

1. Interceptor in SpringMVC 1.1. Practice goals Add a hyperlink to the "User Name" location displayed on the home page, and click to enter the "Personal Center". by/user/info.doPat...

The difference between Spring interceptor and filter

An interceptor is an enhancement of functionality by uniformly intercepting requests sent from the browser to the server. Usage scenario: Solving the common problem of the request (garbled problem, pe...

More Recommendation

Spring Boot interceptor, filter, listener

Using Web frameworks at work, you can't avoid dealing with these concepts, do a summary, and say interceptors, filters, and listeners in one go. GitHub source address 1. Interceptor, filter, listener ...

AOP/Spring AOP/Filter/Interceptor

AOP AOP, face-oriented programming, is a programming idea. Common AOP technology in Java Spring AOP Spring AOP, an implementation of AOP, uses a proxy mode. Filter Filter (filter) is the specification...

The difference between Filter and Interceptor in Spring

Interceptor The main role: intercept user requests, processing, such as judging user login status, permission verification, as long as the controller request processing, is throughHandlerInterceptor。 ...

Spring boot configuration interceptor and filter

Interceptor Customize a normal interceptor Here is the same as before to create a normal interceptor Create a configuration class Create a configuration class, add the relevant interceptor in the conf...

Spring filter interceptor AOP difference

Introduction These days when I reviewed Spring's AOP, I was a bit curious about the relationship between filters, interceptors, and AOPs, so the records were backed up. When implementing some common l...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top