@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
@Resource
StringRedisTemplate stringRedisTemplate;
/**
* true 表示继续流程,false表示中断
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("preHandle...");
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
log.info("token为空,请求被拦截");
throw new BusinessException("token为空,请求被拦截了");
}
String redisToken = null;
try {
redisToken = stringRedisTemplate.opsForValue().get(token);
} catch (Exception e) {
e.printStackTrace();
}
if (redisToken == null) {
log.error("token无效, 请求被拦截");
throw new BusinessException("token无效, 请求被拦截");
} else {
log.info("已登录: {}", redisToken);
}
return true;
}
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
// TODO exclude路径在配置文件读取
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserLoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns( "/system/admin/user/login", "/system/admin/user/logout",
"/system/admin/kaptcha");
}
}
前端输出
后端输出:
22.538 ERROR c.c.s.i.UserLoginInterceptor :47 token无效, 请求被拦截
想用另一种方法实现用户拦截,这是我写的拦截器,在server模块,逻辑跟过滤器一样,从后端的返回值和日志看拦截像是成功了。
但是不知道为什么前端页面还是能读取到静态的资源。
Interceptor拦截器能不能代替过滤器?