作用:通过拦截器中执行通用的代码逻辑,以减少控制器中代码的冗余
特点:
类 implements HandlerInterceptor
注册到 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");
}
}
定义了多个拦截器,每个拦截器又都有三个方法,执行顺序如下(类比进栈和出栈):