拦截器的使用步骤:

  第一步,实现HandlerInterceptor接口,该接口有三个方法preHandle 、postHandle 、afterCompletion 

   (1)preHandle在controller执行之前调用

   (2)postHandle在controller执行之后,页面渲染之前调用

   (3)afterCompletion在页面渲染之后调用,一般用于资源清理操作

  第二步,继承WebMvcConfigurationSupport或者实现WebMvcConfigurer,重写他们的addInterceptors方法。把上一步的拦截器加进去。

  pom.xml

<?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>com.edu.spring</groupId>
    <artifactId>springboot_web</artifactId>
    <version>1.0.0</version>

    <name>springboot_web</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    <parent> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>2.0.4.RELEASE</version> 
    </parent>
    <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>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>
View Code

相关文章: