search
HomeJavajavaTutorialDetailed introduction to Spring MVC interceptor
Detailed introduction to Spring MVC interceptorSep 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
Java Spring怎么实现定时任务Java Spring怎么实现定时任务May 24, 2023 pm 01:28 PM

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

Java axios与spring前后端分离传参规范是什么Java axios与spring前后端分离传参规范是什么May 03, 2023 pm 09:55 PM

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

Spring Boot与Spring Cloud的区别与联系Spring Boot与Spring Cloud的区别与联系Jun 22, 2023 pm 06:25 PM

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

Spring 最常用的 7 大类注解,史上最强整理!Spring 最常用的 7 大类注解,史上最强整理!Jul 26, 2023 pm 04:38 PM

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

Java Spring框架创建项目与Bean的存储与读取实例分析Java Spring框架创建项目与Bean的存储与读取实例分析May 12, 2023 am 08:40 AM

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

从零开始学Spring Cloud从零开始学Spring CloudJun 22, 2023 am 08:11 AM

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

Java Spring Bean生命周期管理的示例分析Java Spring Bean生命周期管理的示例分析Apr 18, 2023 am 09:13 AM

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有哪些spring设计模式有哪些Dec 29, 2023 pm 03:42 PM

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools