How to implement spring MVC interceptor / spring MVC interceptor of SSM? What is the function of interceptors?

Write before:
Record your spring MVC learning journey. If you don't understand it, it is recommended to read it first Previous blogs , detailed codes can be found in My Gitee warehouse SSM learning Clone download learn to use!

2.5 spring MVC interceptor

2.5.1 function of spring MVC interceptor

Interceptor is similar to the Filter in Servlet, which is used to preprocess and post process the processor.
Interceptors are connected into a chain in a certain order, which is called interceptor chain. When accessing the intercepted method or field, the interceptors in the interceptor chain will be called in the order defined before, which is also the embodiment of AOP idea.

2.5.2 difference between interceptor and filter

differenceScope of useto configureInterception range
FilterIs a Servlet specification that can be used in any Java Web projectConfigure in the URL pattern in the web.xml file/*All access resources are blocked only after configuration
InterceptorIt is unique to spring MVC and can only be used when using its frameworkConfigure MVC: mapping path = "" / > in the spring mvc.xml fileAll resources can be intercepted only after configuration, but the parts that do not need to be intercepted can be excluded through the < MVC: exclude mapping path = "" / > tag

2.5.3 interceptor method

Interceptors are user-defined, but they all need to implement the interface HandlerInterceptor. Generally, three methods need to be rewritten, namely:

  • preHandle(). The target method executes it before execution. The return value is Boolean. If it is false, all the following methods will not be executed. It is generally used to judge whether it has a license during access and prevent malicious access
  • postHandle(). The target method is executed after execution, and the dispatcher servlet is executed before view processing. The view object can be modified and returned
  • After completion (). The whole interception method is executed after execution, that is, the dispatcher servlet executes after view processing

Note: these three methods are the concrete embodiment of the AOP principle. The target method is the tangent point and the method in the controller is the tangent plane
Execution process:

2.5.4 code operation

2.5.4.1 project preparation

according to [#### 2.1.4 project construction] Create a new controller class. The business methods are as follows:

@RequestMapping("/target1")  
public ModelAndView show()  
{  
     System.out.println("target resources are running!");  
	 ModelAndView modelAndView = new ModelAndView();  
	 modelAndView.addObject("userName","demo");  
	 modelAndView.setViewName("index");  
	 return modelAndView;  
}

Configure the spring mvc.xml view parser and annotation scanning, as shown in the figure below
Configure the Servlet in the web.xml file, as shown in the figure! [![[Pasted image 20211203190822.png]](https://img-blog.csdnimg.cn/709e778830fd4d828b4acd1156d6e686.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6Iqx6Iqx55qE5bCP6ISR55Oc,size_20,color_FFFFFF,t_70,g_se,x_16)
Display the key value pair userName added by the controller method to index.jsp, as shown in the figure below
The final implementation effect is shown in the figure

2.5.4.2 writing interceptors

Create a new interceptor MyInterceptor, implement the HandlerInterceptor interface and rewrite the method as follows:

public class MyInterceptor1 implements HandlerInterceptor {  
// Intercept before target method execution  
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
       System.out.println("-------------preHandle---------");  
		return true; 
}  
// Intercept after the target method is executed, and execute before the view object is executed  
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {  
       System.out.println("-------------postHandle---------");  
}  
 
// The whole process shall be implemented after all the processes are completed  
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {  
       System.out.println("-------------afterCompletion---------");  
}  
}

2.5.4.3 configure interceptors

Configure the interceptor just written in the springmvc.xml file, as follows:

<!-- Configuring Interceptors -->  
<mvc:interceptors>  
   	<!-- Configure an interceptor-->  
   	 <mvc:interceptor>  
   			<!-- Intercept path-->  
   			 <mvc:mapping path="/**"/>  
   			<!-- Interceptor class-->  
   			 <bean class="com.demo.Interceptor.MyInterceptor1"/>  
   	 </mvc:interceptor>  
</mvc:interceptors>

2.5.4.4 testing

After running the project and accessing target1, the console will appear as shown in the figure

2.5.5 operation of multiple interceptors

2.5.5.1 writing interceptors

Write as before

2.5.5.2 configure interceptors

Configure in the previously configured < MVC: interceptors > < / MVC: interceptors >, as shown in the figure

2.5.5.3 testing

It is the same as the single interceptor test, as shown in the figure

It can be seen that multiple interceptors are intercepted layer by layer!

Keywords: Java Programming Spring MVC mvc intellij-idea

Added by sader on Fri, 03 Dec 2021 22:25:19 +0200