Implement a logging method using the Spring MVC interceptor

  • 2020-06-19 10:22:02
  • OfStack

I've been working on the Spring MVC interceptor, so today is a study note! Those who want to know about logging using the Spring MVC interceptor can refer to it. I hope this article has been helpful to you.

1. Define a class to implement HandlerInterceptor, such as:


public class MyInterceptors implements HandlerInterceptor{ 
  /** 
   *  Called after rendering the view;  
   *  It can be used to free up resources  
   */  
  public void afterCompletion(HttpServletRequest arg0, 
      HttpServletResponse arg1, Object arg2, Exception arg3) 
      throws Exception { 
    // TODO Auto-generated method stub 
    System.out.println("MyInterceptors afterCompletion"); 
  } 
  /** 
   *  This method is called after the target method and before rendering the view.  
   *  You can make changes to properties or views in the request domain  
   * 
   */ 
  public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, 
      Object arg2, ModelAndView arg3) throws Exception { 
    // TODO Auto-generated method stub 
    System.out.println("MyInterceptors postHandle");     
  } 
 
  /** 
   *  Consider permissions, logging, transactions, and so on  
   *  The method is called before the target method is called;  
   *  If the return TURE, The subsequent interceptor and target methods are then called  
   *  If the return FALSE, Subsequent interceptor and target methods are not invoked  
   * 
   */ 
  public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, 
      Object arg2) throws Exception { 
    // TODO Auto-generated method stub 
    HandlerMethod handlerMethod = (HandlerMethod) arg2;  
    System.out.println("MyInterceptors preHandle  Call method name: "+handlerMethod.getMethod().getName()); 
    /* 
       write 1 A diary class and Service , save the required attributes to the database        
    */ 
 
    return true; 
  } 
 
} 

2. Assembled in ES13en.xml


<!--  Assembly interceptor  --> 
<mvc:interceptors> 
  <mvc:interceptor> 
  <mvc:mapping path="/*"/> 
    <bean class="com.datatub.springmvc.interceptors.MyInterceptors"></bean> 
  </mvc:interceptor> 
</mvc:interceptors> 

Related articles: