拦截器
- 1. 拦截器概念
- 2. 拦截器入门案例
- 2.1 环境准备
- 2.2 拦截器开发
- 步骤1: 创建拦截器类
- 步骤2: 配置拦截器类
- 步骤3: SpringMVC添加SpringMvcSupport包扫描和interceptor包扫描
- 步骤4: 简化SpringMvcSupport的编写
- 5 测试
- 3. 拦截器参数解析(了解)
- 3.1 前置处理方法
- 3.2 后置处理方法
- 3.3 完成处理方法
- 4. 拦截器链配置
1. 拦截器概念
(1) 浏览器发送一个请求会先到Tomcat的web服务器
(2) Tomcat服务器接收到请求以后,会去判断请求的是静态资源还是动态资源
(3) 如果是静态资源,会直接到Tomcat的项目部署目录下去直接访问
(4) 如果是动态资源,就需要交给项目的后台代码进行处理
(5) 在找到具体的方法之前,我们可以去配置过滤器(可以配置多个Filter),按照顺序进行执行
(6) 然后进入到到中央处理器(SpringMVC中的内容),SpringMVC会根据配置的规则进行拦截
(7) 如果满足规则,则进行处理,找到其对应的controller类中的方法进行执行,完成后返回结果
(8) 如果不满足规则,则不进行处理
拦截器要做的事情:
- 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
- 作用:
- 在指定的方法调用前后执行预先设定的代码
- 阻止原始方法的执行
- 拦截器就是用来做增强
注意区分过滤器和拦截器:
- 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
- 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强
2. 拦截器入门案例
2.1 环境准备
步骤1:创建一个Web的Maven项目
步骤2:在pom.xml中添加所需的jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springMVC_12_interceptor</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
步骤3:编写Controller
package com.itheima.controller;
import com.itheima.domain.Book;
import org.springframework.web.bind.annotation.*;
/**
* @Author Mr.Lu
* @Date 2023/2/11 15:16
* @ClassName BookController
* @Version 1.0
*/
@RestController
@RequestMapping("/books")
public class BookController {
@PostMapping
public String save(@RequestBody Book book){
System.out.println("book save ..." + book);
return "{'module':'book save'}";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("book delete..." + id);
return "{'module':'book delete'}";
}
@PutMapping
public String update(@RequestBody Book book){
System.out.println("book update ... " + book);
return "{'module':'book update'}";
}
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("book getById ... " + id);
return "{'module':'book getById'}";
}
@GetMapping
public String getAll(){
System.out.println("book getAll...");
return "{'module':'book getAll'}";
}
}
步骤4:创建模型类Book
package com.itheima.domain;
/**
* @Author Mr.Lu
* @Date 2023/2/11 15:12
* @ClassName Book
* @Version 1.0
*/
public class Book {
private String name;
private double price;
public Book() {
}
public Book(String name, double proce) {
this.name = name;
this.price = proce;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getProce() {
return price;
}
public void setProce(double proce) {
this.price = proce;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", proce=" + price +
'}';
}
}
步骤5:创建对应的配置类
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
public class SpringMvcConfig {
}
package com.itheima.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
import javax.servlet.Filter;
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
/**
* 加载springmvc配置类
*
* @return
*/
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
/**
* 设置由springmvc控制器处理的请求映射路径
*
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
/**
* 加载spring配置类
*
* @return
*/
@Override
protected WebApplicationContext createRootApplicationContext() {
// AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// ctx.register(SpringConfig.class);
// return ctx;
return null;
}
// 乱码处理
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
2.2 拦截器开发
步骤1: 创建拦截器类
在com.itheima目录下面建一个interceptor包,在interceptor包下面建一个实现HandlerIntercepror接口的类,并重写里面的额三个方法。
注意: 拦截器中的preHandler
方法,如果返回true,则代表放行,会执行原始Controller类中要请求的方法,如果返回false,则代表拦截,后面的就不会再执行了。
当有拦截器后,请求会先进入preHandle方法,
-
如果方法返回true,则放行继续执行后面的handle[controller的方法]和后面的方法
-
如果返回false,则直接跳过后面方法的执行。
package com.itheima.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 定义拦截器类,实现HandlerInterceptor接口
// 注意当前类必须受Spring容器控制
@Component
public class ProjectInterceptor implements HandlerInterceptor {
@Override
// 原始方法调用前执行的内容
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
return true;
}
@Override
// 原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
@Override
// 原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
步骤2: 配置拦截器类
在config目录下创建一个类来配置拦截器类
package com.itheima.config;
import com.itheima.interceptor.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @Author Mr.Lu
* @Date 2023/2/12 15:13
* @ClassName SpringMvcSupport
* @Version 1.0
*/
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired(required = false)
private ProjectInterceptor projectInterceptor;
// @Override
// protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
// }
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 配置拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*"); // 为可变参数,可以写几种路径
}
}
步骤3: SpringMVC添加SpringMvcSupport包扫描和interceptor包扫描
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.interceptor", "com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
步骤4: 简化SpringMvcSupport的编写
让SpringMvcConfig类实现WebMvcConfigurer接口。
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
// 实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
}
5 测试
访问http://localhost:8080/books
访问http://localhost:8080/books/666
3. 拦截器参数解析(了解)
3.1 前置处理方法
原始方法之前运行preHandle
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
- request:请求对象
- response:响应对象
- handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装
3.2 后置处理方法
原始方法运行后运行,如果原始方法被拦截(前置方法返回false),则不执行
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
modelAndView:如果处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整
3.3 完成处理方法
拦截器最后执行的方法,无论原始方法是否执行(只要前置方法返回true,那么完成处理方法就一定执行)
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception {
System.out.println("afterCompletion");
}
4. 拦截器链配置
步骤1:创建拦截器类:实现接口,并重写接口中的方法
拦截器2: ProjectInterceptor2
package com.itheima.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author Mr.Lu
* @Date 2023/2/12 15:09
* @ClassName ProjectInterceptor
* @Version 1.0
*/
// 定义拦截器类,实现HandlerInterceptor接口
// 注意当前类必须受Spring容器控制
@Component
public class ProjectInterceptor2 implements HandlerInterceptor {
@Override
// 原始方法调用前执行的内容
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...222");
return true;
}
@Override
// 原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...222");
}
@Override
// 原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...222");
}
}
拦截器3:ProjectInterceptor3
package com.itheima.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author Mr.Lu
* @Date 2023/2/12 15:09
* @ClassName ProjectInterceptor
* @Version 1.0
*/
// 定义拦截器类,实现HandlerInterceptor接口
// 注意当前类必须受Spring容器控制
@Component
public class ProjectInterceptor3 implements HandlerInterceptor {
@Override
// 原始方法调用前执行的内容
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...333");
return true;
}
@Override
// 原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...333");
}
@Override
// 原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...333");
}
}
步骤2:配置拦截器类
package com.itheima.config;
import com.itheima.interceptor.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @Author Mr.Lu
* @Date 2023/2/12 15:13
* @ClassName SpringMvcSupport
* @Version 1.0
*/
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired(required = false)
private ProjectInterceptor projectInterceptor;
@Autowired(required = false)
private ProjectInterceptor2 projectInterceptor2;
@Autowired(required = false)
private ProjectInterceptor3 projectInterceptor3;
// @Override
// protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
// }
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 配置拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books", "/books/*");
registry.addInterceptor(projectInterceptor3).addPathPatterns("/books", "/books/*");
}
}
步骤3:运行程序,观察顺序
拦截器执行的顺序是和配置顺序有关,先进后出。
- 当配置多个拦截器时,形成拦截器链
- 拦截器链的运行顺序参照拦截器添加顺序为准
- 当拦截器中出现对原始处理器的拦截,后面的拦截器均终止运行
- 当拦截器运行中断,仅运行配置在前面的拦截器的afterCompletion操作
注:
-
当ProjectInterceptor,ProjectInterceptor2,ProjectInterceptor3中的preHandle方法都返回true时,拦截器链执行顺序为:pre1, pre2, pre3, Controller, post3, post2, post1, after3, after2, after1.
-
当ProjectInterceptor,ProjectInterceptor2中的preHandle方法返回true,ProjectInterceptor3中的preHandle方法返回false时,拦截器链执行顺序为:pre1, pre2, pre3, after2, after1.
-
当ProjectInterceptor中的preHandle方法返回true,ProjectInterceptor2中的preHandle方法返回false时,拦截器链执行顺序为:pre1, pre2, after1.
-
当ProjectInterceptor中的preHandle方法返回false时,拦截器链执行顺序为:pre1