【Spring Boot教程】(十九):Spring Boot中的拦截器开发

如果在每个控制器(controller)方法中都使用session.grtAttribute("user")会显得十分冗余,我们可以使用拦截器,请求先经过拦截器,通过了然后再进入控制器。

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

特点:

  • 只能拦截控制器相关请求,不能拦截静态资源和页面相关情况(css,js…)
  • 请求发送经过拦截器,响应回来同样经过拦截器
  • 拦截器可以中断用户请求
  • 拦截器可以针对性拦截某些控制器请求

拦截器开发流程:

# 1、类(xxxInterceptor) implements HandlerInterceptor
	preHandler----预先处理,返回值true放行到controller中,false中断请求同时在原页面
	postHandler----请求过程中处理,即controller执行之后的操作
	afterCompletion----响应之后执行
# 2、springboot中配置拦截器
	注册到springboot拦截数组中,方法是写一个配置类

拦截器:

public class MyInterceptor implements HandlerInterceptor {
    
    
	//实现你想要的接口即可,可以只实现一个,一般放在interceptor包下
}

配置类——1.x版本:

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("/**")//定义拦截请求
                .excludePathPatterns("/hello/**");//排除拦截请求
    }
}

配置类——2.x版本:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    
    
	//即继承变成了实现接口,JDK8有了接口的默认实现,因此只实现一个方法也是可以的
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new MyInterceptor())//添加拦截器
                .addPathPatterns("/**")//定义拦截路径
                .excludePathPatterns("/hello/**");//排除拦截路径
    }
}

拦截器执行顺序:

配置类中先添加的inter1,再添加的inter2

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46521785/article/details/114924306