今天配置WebMvcConfigurer拦截器,无论怎么配置,都没有生效。代码如下:
@Configuration
@EnableConfigurationProperties(JwtConfig.class)
public class WebAppConfigurer implements WebMvcConfigurer {
@Autowired
private JwtConfig props;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置登录拦截器
registry.addInterceptor(new UserInterceptor(props)).addPathPatterns("/**");
}
}
public class UserInterceptor implements HandlerInterceptor {
private JwtConfig props;
//定义一个线程域,存放登录的对象
private static final ThreadLocal<Account> user = new ThreadLocal<>();
public UserInterceptor() {
super();
}
public UserInterceptor(JwtConfig props) {
this.props = props;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//查询Token
String token = CookieUtils.getCookieValue(request, props.getCookieName());
if (StringUtils.isBlank(token)) {
//用户未登录,返回401,拦截
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
//用户已登录,获取用户信息
try {
Account userInfo = JwtUtils.getUserInfo(props.getPublicKey(), token);
//放入线程域中
user.set(userInfo);
return true;
} catch (Exception e) {
//抛出异常,未登录
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//过滤器完成后,从线程域中删除用户信息
user.remove();
}
/**
* 获取登陆用户
* @return
*/
public static Account getLoginUser() {
return user.get();
}
}
通过debug测试加载顺序,发现
WebAppConfigurer的addInterceptors方法一直没有加载到,看了下自己的springboot启动类,其中配置有scanBasePackages,可能因为这个配置所有component没有扫描上,最后又加上了拦截器配置所在的包@ComponentScan(basePackages={"com.zc.test.item.*"}),启动正常!
@SpringBootApplication(scanBasePackages = "com.zc.test.*")
@ComponentScan(basePackages={"com.zc.test.item.*"})
public class ItemApplication {
public static void main(String[] args) {
SpringApplication.run(ItemApplication.class, args);
}
}