Interceptors are powerful and can be used for logging, permission checking and performance testing before and after the deep method. It is almost an indispensable part of the project. This article will implement the configuration of Spring Boot custom interceptors.

Theoretical guidance

Q: How do Spring Boot configure interceptors?

A: Configuring an interceptor is a two-step process.

  1. Custom interceptor, implementation of the HandlerInterceptor interface. This interface consists of three methods: preHandle is executed before the request is executed, postHandler is executed after the request is completed, but only after the preHandle method returns true, and afterCompletion is executed after the view has been rendered. PreHandle is also required to return true. This method is usually used for tasks such as cleaning up resources.

  2. Register interceptors. Determines the interceptor and the URL to intercept. We need to inherit WebMvcConfigurationSupport rewrite addInterceptor method, WebMvcConfigureAdapter already out of date!!!!!

Code implementation

Directory structure:

The TimeCostInterceptor is a fully functional interceptor, which needs to use util in the utility class. Because there is more code, you can check the source code in GitHub.

Specific code:

MyInterceptor.java

public class MyInterceptor implements HandlerInterceptor {

    /** * preHandle executes before Controller, returns true, continues Contorller * returns false, interrupts. * /
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        // Proceed only if true is returned and false is returned to cancel the current request
        long startTime = System.currentTimeMillis();
        httpServletRequest.setAttribute("startTime", startTime);
        return true;
    }

    /** * postHandle is executed after the request is completed, but before the render ModelAndView returns
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        long startTime = (Long) httpServletRequest.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;
        StringBuilder sb = new StringBuilder(1000);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        sb.append("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --").append(date).append("-------------------------------------\n");
        sb.append("URI : ").append(httpServletRequest.getRequestURI()).append("\n");
        sb.append("CostTime : ").append(executeTime).append("ms").append("\n");
        sb.append("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        System.out.println(sb.toString());
    }

    /** * afterCompletion is executed after the entire request is completed
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}}Copy the code

RegisterInterceptor.java

/ * * * inherit to the WebMvcConfigurationSupport rewrite addInterceptor method for registering the interceptor * WebMvcConfigureAdapter is outdated!!!!! * /
@Configuration
public class RegisterInterceptor extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/ * *");
        super.addInterceptors(registry); }}Copy the code

Interception effect


update

Cross domain access

Because of the JavaScript same-origin policy, any protocol, domain name, or port that sends the requested URL is different from the current page address. For details, see the following table (from javascript Cross-domain resource Summary and solutions) :

URL instructions Whether to allow communication
www.a.com/a.jswww.a.com/b.js Under the Same domain allow
www.a.com/lab/a.jswww.a.com/script/b.js Different folders under the same domain name allow
www.a.com:8000/a.jswww.a.com/b.js Same domain name, different port Don’t allow
www.a.com/a.jswww.a.com/b.js Same domain name, different protocol Don’t allow
www.a.com/a.jshttp://70.32.92.74/b.js The domain name and corresponding IP address of the domain name Don’t allow
www.a.com/a.jsscript.a.com/b.js The primary domain is the same, but the subdomain is different Don’t allow
www.a.com/a.jsa.com/b.js Same domain name, different secondary domain name (same as above) Disallow (access is also disallowed in the case of cookies)
www.cnblogs.com/a.jswww.a.com/b.js Different domain name Don’t allow

The above code can implement the basic function of the interceptor, but this is not cross-domain access, the front-end request interface will error: XMLHttpRequest cannot loadhttp://xxx/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

The solution is to set the access-Control-allow-origin header to * or set it to the same Origin as the request header.

① Add a method to the interceptor to set the request header.

    public void crossDomain(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials"."true");
    }
Copy the code

② Call this method in the preHandle.

   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        crossDomain(request, response);
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }
Copy the code

Full code: GItHub address