在第一节写SpringMVC的运行原理的时候讲过,每个组件之间都是按部就班的运行的,如下图(部分图):
都是按步骤每步每步走,当请求没有发送,前端控制器没收到请求,就不会去找处理器映射器。Controller是使用了Servlet为核心,因为是SpringMVC使用了Servlet为核心,那么每个请求都会拦截下来运行,那么我们想要在它运行前后先拦截下来进行条件判断,这样就出现了拦截器。那怎么用代码实现使用拦截器呢?首先搭建环境
Maven配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${
spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version> <scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11<