Use the interceptor of Spring to monitor the execution time of each Controller or method

  • 2021-12-04 10:18:07
  • OfStack

Directory Spring Interceptor monitors the execution time of each Controller or method. First, write a class (TestInterceptor), then spring configuration file. Interceptor, the execution time of three methods. Interceptor, three methods are

The Spring interceptor monitors the execution duration of each Controller or method

First write a class (TestInterceptor)

Let him inherit HandlerInterceptorAdapter and override three of its methods, such as:


package com.wechat.test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by lenovo on 2017/3/14.
 */
public class TestInterceptor extends HandlerInterceptorAdapter {
    private long time;
    private int openingTime;
    private int closingTime;
    private String mappingURL;// Use regular mapping to the path to be intercepted 
    public void setOpeningTime(int openingTime) {
        this.openingTime = openingTime;
    }
    public void setClosingTime(int closingTime) {
        this.closingTime = closingTime;
    }
    public void setMappingURL(String mappingURL) {
        this.mappingURL = mappingURL;
    }
    /**
     * 1. Enter Controller Method is executed before the 
     * @param request
     * @param response
     * @param handler
     * @return  The return value is true You can continue execution when Controller , preHandle() And afterCompletion() , for false Stops executing any method when. 
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        time = System.currentTimeMillis();
        String url=request.getRequestURL().toString();
        if(mappingURL==null || url.matches(mappingURL)){
            Calendar c=Calendar.getInstance();
            c.setTime(new Date());
            int now=c.get(Calendar.HOUR_OF_DAY);
            if(now<openingTime || now>closingTime){
                request.setAttribute("msg", " Registration opening hours: " + openingTime + " : 00-" + closingTime + " : 00");
//                request.getRequestDispatcher("/msg.jsp").forward(request, response);
                return false;
            }
            return true;
        }
        return true;
    }
    /**
     * 2.Controller Execute when the method completes execution but the view rendering is not performed 
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
    /**
     * 3. The view rendering is complete (the whole request is finished) execution 
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(" Request processing is complete! Time: "+(System.currentTimeMillis() - time)+"ms");
        super.afterCompletion(request, response, handler, ex);
    }
}

Next is the spring configuration file


<!-- Interceptor -->
<mvc:interceptors>
   <mvc:interceptor>
      <!-- Configure which requests are intercepted -->
      <mvc:mapping path="/**"/>
      <bean class="com.wechat.test.TestInterceptor">
         <!-- Write values for parameters in this class -->
         <property name="openingTime" value="16" />
         <property name="closingTime" value="18" />
         <property name="mappingURL" value=".*/index" />
      </bean>
   </mvc:interceptor>
</mvc:interceptors>

Execution timing of three methods of interceptor

The three methods of interceptor are

1. preHandle

Pretreatment callback method, pretreatment of the processor (such as login check), the third parameter for the response of the processor (such as the specific Controller implementation);

Return value: true indicates continuing the process (such as calling the next interceptor or processor); false means that the process is interrupted (such as login check failure) and other interceptors or processors will not be called. At this time, we need response to generate a response;

2. postHandle

Post-processing callback method, which realizes the post-processing of the processor (but before rendering the view). At this time, we can process the model data or the view through modelAndView (model and view objects), and modelAndView may also be null.

3. afterCompletion

Callback method when the whole request is processed, that is, callback when the view is rendered. For example, in performance monitoring, we can record the end time and output the consumption time here, and we can also clean up some resources, similar to finally in try-catch-finally, but only call afterCompletion of the interceptor that preHandle returns true in the processor execution chain.

First, the user requests to reach the front-end controller DispatcherServlet, the front-end controller finds the processor mapper, finds the corresponding processor handler according to the requested method, generates the execution chain of the interceptor and the execution sequence of handler, and gives it to DispatcherServlet,

dispatcherServlet finds the corresponding processor adapter for processing.

prehandler is executed before the request is processed. The return value of this method is of Boolean Boolean type. When it returns false, it indicates that the request is finished, and the subsequent Interceptor and Controller will not be executed again; When the return value is true, the preHandle method of the next Interceptor will continue to be called, and if it is the last Interceptor, the method in the currently requested Controller will be called.

The postHandler method executes after the current request is processed, that is, after the method call in Controller, but it is called before DispatcherServlet performs the view return rendering, so we can operate on the ModelAndView object after Controller processing in this method.

afterCompletion This method will be executed after the entire request is completed, that is, after DispatcherServlet has rendered the corresponding view. The main purpose of this method is to clean up resources. Resource release like exception handling will be placed in this step.

The execution order of multiple interceptors is: preHandler of interceptor A-- > preHandler of interceptor B-- > postHandler for B-- > postHandler for A-- > afterCompletion of B-- > afterCompletion for A


Related articles: