Two implementation methods of spring filter (MVC)

1. Concept

The Interceptor of Spring MVC is similar to the Filter of Java Servlet. It is mainly used to intercept users' requests and handle them accordingly. It is usually used in functions such as permission verification, logging request information, judging whether users log in or not.

Defining an interceptor in the Spring MVC framework requires defining and configuring the interceptor. There are two ways to define an Interceptor: one is to define it by implementing the HandlerInterceptor interface or by inheriting the implementation class of the HandlerInterceptor interface; The other is defined by implementing the WebRequestInterceptor interface or the implementation class that inherits the WebRequestInterceptor interface.

2. Distinction

Both interceptors are provided by Spring, but WebRequestInterceptor only serves the purpose of request verification, indicating that the request will be received by WebRequestInterceptor implementation class. It will not intercept illegal requests like the HandlerInterceptor interceptor.

3. Method of two interfaces

3.1. Method of HandlerInterceptor interface

public interface HandlerInterceptor {

	// Intercept the request when the Controller gets it. If the request is not released, the Controller cannot get the request
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
    
	//This method is called when the Controller finishes processing the request for view jump
    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

	// Call this method after the view jump is complete
    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

The methods in the HandlerInterceptor interface are all default, which means that the method is not forced to be rewritten. But we usually rewrite these three methods.

3.2. Method of WebRequestInterceptor interface

public interface WebRequestInterceptor {

	/** Controller Call this method to intercept the request before getting the request,
		However, it will not intercept requests without releasing them like HandlerInterceptor.
	**/
    void preHandle(WebRequest request) throws Exception;

	// This method is called after the Controller processes the request
    void postHandle(WebRequest request, @Nullable ModelMap model) throws Exception;

	// This method is called after the view jumps.
    void afterCompletion(WebRequest request, @Nullable Exception ex) throws Exception;
}

WebRequestInterceptor is the same except that the preHandle method is different from the preHandle method in the HandlerInterceptor interface.
In addition, the methods in WebRequestInterceptor are of Void type. When implementing this interface, you must override all methods inside the interface. (the foundation in the foundation cannot be forgotten)
However, WebRequestInterceptor is spring's encapsulation of HttpServletRequest. Therefore, the content processed by WebReqeustInterceptor will be recorded in HttpServletRequest.

4,springMVC.xml configuration

   <!--Configuring Interceptors -->
    <mvc:interceptors>
        <bean class="utils.Interceptor"/> <!--Configure a global interceptor to intercept all requests-->
        <mvc:interceptor> <!--Configure interceptors for specific requests to intercept specified requests-->
            <mvc:mapping path="/**"/> <!--Configure the path intercepted by the current specific interceptor-->
            <mvc:exclude-mapping path="/login"/> <!--The specified request does not need to be intercepted-->
            <bean class="utils.Interceptor"/> <!--Which interceptor intercepts the configuration path-->
        </mvc:interceptor>

        <mvc:interceptor>
            <mvc:mapping path="/loginOut"/>
            <mvc:exclude-mapping path="/login"/>
            <bean class="utils.WebInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

The above contents must be configured, otherwise the interceptor is invalid and can be configured according to needs, but the configuration sequence of interceptors has strict requirements:

<mvc:interceptor>
   <mvc:mapping path="Blocked requests"/>
   <mvc:exclude-mapping path="Non intercepted requests"/>
   <bean class="Path of interceptor object"/>
</mvc:interceptor>

5. Don't say much, code

Focus, or I'm on earth and you're in outer space.

5.1. WebInterceptor implementation class

public class Interceptor implements HandlerInterceptor {

    private static int preFlag = 0, postFlag = 0, afterFlag = 0;

    // Intercept the request when the Controller gets it. If the request is not released, the Controller cannot get the request
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Interceptor intercepted the request, the requested URI For:" + request.getRequestURI());
        System.out.println("Interception times=" + (++preFlag));
        return true; // Release request
        // If the interceptor does not release the request, the request will always be intercepted
    }

    // After the Controller processes the request and before the view is rendered, the interceptor verifies
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Interceptor starts parsing request" + modelAndView.getViewName());
        System.out.println("Number of parsing requests=" + (++postFlag));
    }

    // Called after the view rendering is complete
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Request complete");
        System.out.println("Render times=" + (++afterFlag));
    }
}

springMVC.xml configuration

    <mvc:interceptors>
        <bean class="utils.Interceptor"/> <!--Configure a global interceptor to intercept all requests-->
        <mvc:interceptor> <!--Configure interceptors for specific requests to intercept specified requests-->
            <mvc:mapping path="/**"/> <!--Configure the path intercepted by the current specific interceptor-->
            <mvc:exclude-mapping path="/login"/> <!--The specified request does not need to be intercepted-->
            <bean class="utils.Interceptor"/> <!--Which interceptor intercepts the configuration path-->
        </mvc:interceptor>
    </mvc:interceptors>

The HandleInterceptor interceptor intercepts the request twice, ha! Why two interceptions?

Spring MVC will think that your request URI is a view name, and then check your view name before rendering the view. If it is a view, it will throw a servvetexception. This error will cause the whole process of dispatcher servlet to restart.

This is the answer I know.

If you don't understand, just look at the picture and see the effect
The HandleInterceptor I configured will intercept all requests

search result

Results of background interception

5.2. WebRequestInterceptor implementation class

public class WebInterceptor implements WebRequestInterceptor {

    @Override
    public void preHandle(WebRequest request) throws Exception {
        System.out.println("Start interception");
    }

    @Override
    public void postHandle(WebRequest request, ModelMap model) throws Exception {
        System.out.println("View request after processing");
    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws Exception {
        System.out.println("Rendering complete");
    }
}

springMVC.xml configuration

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/search"/> <!--Intercept only search requests-->
            <mvc:exclude-mapping path="/login"/> <!--Do not block login requests-->
            <bean class="utils.WebInterceptor"/> <!--Implementation class of interceptor-->
        </mvc:interceptor>
   </mvc:interceptors>

The WebRequestInterceptor always releases requests.
Also take search as an example

According to our use of HandleInterceptor, it is impossible to search, because when the button is pressed, the request will be intercepted by the interceptor, and then see whether the return value of prehandle is false or true. If false, the request will not be released,
The preHandle method in WebRequestInterceptor has no return value, so it will release all requests.
The result is true:

Interception effect of background interceptor

The WebRequestInterceptor interceptor intercepts only once, but it is very different from the handleInterceptor in effect.

I think, for the ape friends who study hard, it is impossible not to know the importance of being able to intercept requests and not being able to intercept requests. No, no, it should not be impossible not to know. 😥

6. OK, start the summary

Filter is an important component in spring MVC. Good use can get twice the result with half the effort. If it is not used properly, hey hey, you know (a few hours will soon pass).
Of course, in addition to using the two filters in spring MVC, you can also use the Filter interface in Servlet to customize the Filter. Which way to use depends on the individual.

Tags: Java Spring Back-end Spring MVC mvc

Posted by csn on Fri, 13 May 2022 02:03:43 +0300