作用:通过拦截器中执行通用的代码逻辑,以减少控制器中代码的冗余

特点:

  1. 拦截器特点只能拦截控制器的相关请求,不能拦截静态资源和页面的相关请求(css、img)
  2. 请求发送经过拦截器响应回来同样经过拦截器
  3. 拦截器中断用户的请求
  4. 拦截器可以针对性拦截某些控制器请求

拦截器开发

类 implements HandlerInterceptor

Spring Boot 配置拦截器

注册到 Spring Boot 拦截数组中

package com.baizhi.config;

import com.baizhi.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()) // 添加拦截器
								.addPathPatterns("/hello/**") // 添加拦截的请求路径
								.excludePathPatterns("/hello/world"); // 排除指定的请求
    }
}

package com.baizhi.config;

import com.baizhi.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfig **implements WebMvcConfigurer** {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/hello/**")
                .excludePathPatterns("/hello/world");
    }
}

多个拦截器的执行顺序

定义了多个拦截器,每个拦截器又都有三个方法,执行顺序如下(类比进栈和出栈):

Untitled