SpringBoot interceptor usage, compared to Struts2 interceptor, SpringBoot interceptor is much more convenient and simple.

You can easily implement the interceptor functionality by writing a few implementation classes, and you don’t need to configure any extra information

Step 1: Create our own interceptor class and implement the HandlerInterceptor interface.

package example.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * custom interceptor 1 ** @author Lin (208017534) * @myblog www.wolzq.com * @create September 20, 2016 */ @controller Public Class The ErrorInterceptor implements HandlerInterceptor {/** * preHandle method is used to implement HandlerInterceptor. As the name suggests, this method is called before the Controller handles it. The SpringMVC Interceptor interceptors are chained. Multiple interceptors can exist at the same time, and SpringMVC will execute them one after the other according to the order in which they are declared. Also, all Interceptor preHandle methods are called before the * Controller method is called. The SpringMVC Interceptor chain structure can also be interrupted by making the preHandle return valuefalse, when the return value of preHandle isfalseThe whole request ends. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(">>>MyInterceptor1>>>>>>> called before request processing (before Controller method call)");
        return true; // Only returntrueBefore it continues down and returnsfalse} /** * This method will only return the value of the current Interceptor preHandletrue"Will be executed. PostHandle is for processor interception. It is executed after the handler has processed *, after the Controller method call, but before the DispatcherServlet renders the view, That is, in this method you can do operations on the ModelAndView. The chain structure of this method is the opposite of the normal access direction, which means that the Interceptor method declared first will be called later. This is a bit like the Struts2 Interceptor execution process. Invocation invocation (Struts2); The Invocation of the Struts2 ActionInvocation is to invoke the next Interceptor * or action invocation. The invocation of the Struts2 Action invocation is to invoke the action invocation before the Interceptor invocation. Anything to be called after the Interceptor is written after the invoke method is called. */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(">>>MyInterceptor1>>>>>>> is called after the request is processed, but before the view is rendered (after the Controller method is called)");
        if(response.getStatus()==500){
            modelAndView.setViewName("/errorpage/500");
        }else if(response.getStatus()==404){
            modelAndView.setViewName("/errorpage/404"); }} /** * This method also requires the return value of the corresponding Interceptor's preHandle method to betrueIs executed. This method is used to clean up resources only when the Interceptor's preHandle method returns a value oftrueIs executed. */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(">>>MyInterceptor1>>>>>>> is called after the whole request is complete, after the DispatcherServlet has rendered the corresponding view (mainly for resource cleanup)"); }}Copy the code

The role of several functions in the interceptor implementation class, and the order in which they are called, are clear, and I won’t cover them here.

Step 2: Create a Java class that inherits WebMvcConfigurerAdapter and rewrite the addInterceptors method. Instantiate our custom interceptor, and add the object manually to the interceptor chain (in the addInterceptors method).

package example.configuration; import example.Interceptor.ErrorInterceptor; import example.Interceptor.MyInterceptor2; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void AddInterceptors (InterceptorRegistry registry) {// Multiple interceptors form a chain of interceptors // addPathPatterns is used to add intercepting rules // excludePathPatterns AddInterceptor (new ErrorInterceptor()).addPathPatterns()"/ * *"); super.addInterceptors(registry); }}Copy the code

At this point, the interceptor is basically implemented. In the example I gave above, it can be implemented on 404 or 500 interceptors.

It should be noted, however, that this interception can sometimes be particularly problematic. For example, if a web page needs to load a lot of images or JS file resources, but there is no such resource, that is, can not find so many resources reported a bunch of 404 errors. If the interception is used only, null pointer exceptions will occur.

In view of this situation, I studied a method to solve such a similar problem.

The solution is to create a class and implement the ErrorController interface so that you can use this class to handle the problem.

Here is the code:

package example.controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainsiteErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";
    @RequestMapping(value=ERROR_PATH)
    public String handleError() {return "errorpage/error";
    }
    @Override
    public String getErrorPath() {
        returnERROR_PATH; }}Copy the code

This will allow interception of error messages such as 404,500 without null-pointer exceptions