search
HomeJavajavaTutorialDetailed introduction to Spring MVC interceptor

Detailed introduction to Spring MVC interceptor

Sep 08, 2017 am 09:43 AM
springintroduceintercept

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);

Execute before generating the view


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

Finally executed, which can be used to release resources


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

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 {   
  略。。。 
}

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>

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>

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>

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></mvc:>, 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-->

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
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
What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

How do you test Java applications for platform compatibility?How do you test Java applications for platform compatibility?May 01, 2025 am 12:09 AM

ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

What is the role of the Java compiler (javac) in achieving platform independence?What is the role of the Java compiler (javac) in achieving platform independence?May 01, 2025 am 12:06 AM

The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.