springboot里边拦截器的运用

Posted 辰辰的小屋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot里边拦截器的运用相关的知识,希望对你有一定的参考价值。

建一个类去继承HandlerInterceptorAdapter

//直接复制就可用 实际项目中已测试
public class AuthorityInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-store");
        response.setCharacterEncoding("UTF-8");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否有token
        LoginRequired checkToken = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解,需要认证
        if (checkToken != null) {
            //这里边去写自己的逻辑  像我就是看请求头中是否携带token
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
    }

2.注解

@Target({ElementType.METHOD})//可用在方法名上
@Retention(RetentionPolicy.RUNTIME)//运行时有效
public @interface LoginRequired {
  //此注解直接打到需要验证的controller层的方法上(@LoginRequired) }

3.再来个配置类

@EnableWebMvc
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要授权
        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public AuthorityInterceptor AuthorityInterceptor() {
        return new AuthorityInterceptor();
    }
}

代码可直接贴 已测试

以上是关于springboot里边拦截器的运用的主要内容,如果未能解决你的问题,请参考以下文章

如何利用redis来进行分布式集群系统的限流设计

springboot+mybatis拦截器不生效问题分析

Java 微服务 day02 源代码 SpringBoot 实战开发 SpringMVC高级配置:拦截器:HandlerExecutionChain

SpringBoot拦截器----addInterceptors

OkHttpInterceptor 从 kotlin 拦截器导航到登录片段

springboot 登录拦截器