Spring Boot实现自定义拦截器

Spring Boot项目如何实现自定义拦截器

  1. 创建拦截器类,实现 HandlerInterceptor接口,并使用@Component注入Spring容器

  2. 重写preHandle(前置拦截)、postHandle、afterCompletion(后置拦截)等方法,实现拦截逻辑

  3. 创建配置类,实现WebMvcConfigurer接口,并使用@Configuration标记当前Bean是配置类

  4. 重写addInterceptors,注册拦截器Bean,定义拦截规则、顺序等

实现一个权限验证拦截器

首先,创建一个拦截器实现类AuthInterceptor.java

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
    
    String token = request.getHeader("token")
    if(StringUtils.isBank(token )){
      throw new RuntimeExpection("缺少token");
    }
    
    //此处是虚代码,具体转换请自己实现
    UserInfo userInfo = (UserInfo)token ;
    UserInfoContext.set(userInfo);

    ...
    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
  
    if (CollectionUtils.isNotEmpty(UserInfoContext.get())){
         UserInfoContext.remove();
    }

  }

}

使用ThreadLocal将登录信息缓存,以便后续使用。

import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
public class UserInfoContext {

    private final static ThreadLocal<UserInfo> User_Info_THREAD_LOCAL = new ThreadLocal<>();

    public static void set(UserInfo userInfo){
        User_Info_THREAD_LOCAL.set(userInfo);
    }

    public static UserInfo  get(){
       return User_Info_THREAD_LOCAL.get();
    }

    public static void remove() {
        User_Info_THREAD_LOCAL.remove();
    }

}

创建配置类,注册拦截器定义信息

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

import javax.annotation.Resource;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private AuthInterceptor authInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor )
                .addPathPatterns("/**")
                .excludePathPatterns("/swagger-resources/**","/swagger-ui.html/**","/doc.html/**")
                .order(Ordered.LOWEST_PRECEDENCE-100);
    }

}

备注:使用aop也可以实现类似功能。

posted @ 2024-08-13 17:18  抒写  阅读(103)  评论(0编辑  收藏  举报