Home Java javaTutorial Detailed introduction to Spring MVC interceptor

Detailed introduction to Spring MVC interceptor

Sep 08, 2017 am 09:43 AM
spring introduce intercept

Spring MVC's interceptor is at the HandlerMapping level. There can be multiple HandlerMappings. Each HandlerMapping can have its own interceptor. Please learn the details through this article.

Spring provides us with :

org.springframework.web.servlet.HandlerInterceptor interface,
org.springframework.web.servlet.handler.HandlerInterceptorAdapter adapter,

implement this interface or Inheriting this class makes it very convenient to implement your own interceptor.

There are the following three methods:

Executed before Action:


 public boolean preHandle(HttpServletRequest request,
  HttpServletResponse response, Object handler);
Copy after login

Execute before generating the view


 public void postHandle(HttpServletRequest request,
  HttpServletResponse response, Object handler,
  ModelAndView modelAndView);
Copy after login

Finally executed, which can be used to release resources


 public void afterCompletion(HttpServletRequest request,
  HttpServletResponse response, Object handler, Exception ex)
Copy after login

respectively Implement preprocessing, postprocessing (Service is called and ModelAndView is returned, but the page is not rendered), and return processing (the page has been rendered)

In preHandle, encoding, security control, etc. can be performed;

In postHandle, you have the opportunity to modify the ModelAndView;

In afterCompletion, you can determine whether an exception has occurred and perform logging based on whether ex is null.

The Object handler in the parameter is the next interceptor.

How to use interceptors?

To customize an interceptor, you need to implement the HandlerInterceptor interface:

Java code


##

public class MyInteceptor implements HandlerInterceptor {   
  略。。。 
}
Copy after login

Spring MVC and Without a total interceptor, all requests cannot be intercepted before and after.

Spring MVC's interceptor is at the HandlerMapping level. There can be multiple HandlerMappings, and each HandlerMapping can have its own interceptor.

When a request executes the implementation classes of the HandlerMapping interface sequentially according to the Order value from small to large, whichever returns first, it is over. The subsequent HandlerMapping will not go away, and the process is completed. . Just move on to the next process.

When will the interceptor be executed? When a request is handed over to a HandlerMapping, the HandlerMapping first looks for a processor to handle the request. If it finds it, it executes the interceptor. After executing the interception, it hands it to the target processor.

If the processor is not found, then this interceptor will not be executed.

There are three ways to configure it in the spring MVC configuration file:

Option 1, (approximate) total interceptor, intercept all urls

Java Code


  <mvc:interceptors> 
  <bean class="com.app.mvc.MyInteceptor" /> 
</mvc:interceptors>
Copy after login

Why is it called "approximate"? As mentioned before, Spring does not have a total interceptor.

An interceptor will be injected into each HandlerMapping. There is always a HandlerMapping that can find the processor, and at most only one processor can be found, so this interceptor will always be executed. Acts as a total interceptor.

If it is a REST-style URL, static resources will also be intercepted.


Option 2, (approximate) total interceptor, intercepts matching URLs.

Xml code


<mvc:interceptors >  
 <mvc:interceptor>  
    <mvc:mapping path="/user/*" /> <!-- /user/* -->  
    <bean class="com.mvc.MyInteceptor"></bean>  
  </mvc:interceptor>  
</mvc:interceptors>
Copy after login

has one more URL match than Solution 1.

If it is a REST-style URL, static resources will also be intercepted.


Option 3, interceptor on HandlerMappint.

If it is a REST-style URL, static resources will not be intercepted. Because we injected the interceptor accurately.

Xml code

##

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">    
 <property name="interceptors">    
   <list>    
     <bean class="com.mvc.MyInteceptor"></bean>   
   </list>    
 </property>    
</bean>
Copy after login

If

is used,

it will automatically register DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter These two beans, so there is no chance to inject the interceptors attribute into it, and the interceptor cannot be specified. Of course, we can manually configure the two beans above without using , and then inject interceptors into the interceptors attribute.


In fact, I don’t recommend using

,

but recommend manually writing detailed configuration files instead <mvc: annotation-driven />, which gives stronger control. How to replace

? What exactly did he do? One sentence

actually did the following work: (excluding adding your own defined interceptor)After we understand this, The control over Spring3 MVC is even stronger, and you can change whatever you want.

Xml code


 <!-- 注解请求映射 --> 
  <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">     
  <property name="interceptors"> 
    <list>  
      <ref bean="logNDCInteceptor"/>  <!-- 日志拦截器,这是你自定义的拦截器 --> 
      <ref bean="myRequestHelperInteceptor"/>  <!-- RequestHelper拦截器,这是你自定义的拦截器-->  
      <ref bean="myPermissionsInteceptor"/> <!-- 权限拦截器,这是你自定义的拦截器-->  
      <ref bean="myUserInfoInteceptor"/> <!-- 用户信息拦截器,这是你自定义的拦截器-->  
    </list>     
  </property>     
</bean>   
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
  <property name="messageConverters">  
    <list>  
      <ref bean="byteArray_hmc" />  
      <ref bean="string_hmc" />  
      <ref bean="resource_hmc" />  
      <ref bean="source_hmc" />  
      <ref bean="xmlAwareForm_hmc" />  
      <ref bean="jaxb2RootElement_hmc" />  
      <ref bean="jackson_hmc" />  
    </list>  
  </property>  
</bean>  
<bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /><!-- 处理.. --> 
<bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter" /><!-- 处理.. --> 
<bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter" /><!-- 处理.. --> 
<bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /><!-- 处理.. --> 
<bean id="xmlAwareForm_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /><!-- 处理.. --> 
<bean id="jaxb2RootElement_hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /><!-- 处理.. --> 
<bean id="jackson_hmc" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /><!-- 处理json-->
Copy after login

The above is the detailed content of Detailed introduction to Spring MVC interceptor. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

See all articles