step1:实现 WebMvcConfigurer 接口,实现 addInterceptors 方法
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//全局登录拦截请求
registry.addInterceptor(new AuthLoginIntercept()).addPathPatterns("/**")
.excludePathPatterns("/file/**")
.excludePathPatterns("/login/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}
}
step2: 集成 HandlerInterceptorAdapter 重写 preHandle 方法
我这用了自定义注解来实现不同的方法或者类,有需要的可以参照下的我另外一篇文章自定义注解
同时也实现了单点登录,具体也可以参考我的文章
@Service
public class AuthLoginIntercept extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
//拦截所有的请求方法,是否需要登录
AuthLogin authLoginMethod = handlerMethod.getMethod().getAnnotation(AuthLogin.class);
if(authLoginMethod != null && !authLoginMethod.needLogin()){
return true;
}
//拦截整个模块,是否需要登录
AuthLogin authLoginClass = handlerMethod.getBeanType().getAnnotation(AuthLogin.class);
if(authLoginClass != null && !authLoginClass.needLogin()){
return true;
}
this.validAuth();
}
return true;
}
//验证登录信息
private void validAuth(){
String token = RequestUtil.getToken();
TokenService tokenService = SpringUtil.getBean(TokenService.class);
tokenService.validateToken(token);
}
}
到这就完成了,有喜欢的小伙伴们可以点个赞,也可以关注下,里面还有其他干货可以看看。