通过springMVC拦截器统一解析token,判断是否有效。可以对请求进行前置或后置处理
/** * 配置拦截器 */ public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取请求头 String token = request.getHeader("Authorization"); //使用工具类判断token是否有效 /*boolean verifyToken = JwtUtils.verifyToken(token); //如果token失效,返回状态码401,拦截 if(!verifyToken){ response.setStatus(401); return false; }*/ //如果token正常,放行 //解析token,获取id和手机号码,构造User对象,存入ThredLocal Claims claims = JwtUtils.getClaims(token); Integer id = (Integer) claims.get("id"); String mobile = (String) claims.get("mobile"); User user=new User(); user.setId(Long.valueOf(id)); user.setMobile(mobile); UserHolder.set(user); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserHolder.remove(); }
/** * 注册拦截器 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TokenInterceptor()) .addPathPatterns("/**")//添加拦截所有 .excludePathPatterns(new String[]{"/user/login","/user/loginVerification"});//排除拦截 } }
//登陆时并无生成token,需进行排除
/** * 工具类:实现向threadlocal存储数据的方法 */ public class UserHolder { //将用户对象存入ThreadLocal private static ThreadLocal<User> tl=new ThreadLocal<>(); public static void set(User user){ tl.set(user); } //从当前线程获取对象 public static User get(){ return tl.get(); } //获取当前用户id public static Long getUserId(){ return tl.get().getId(); } //获取当前用户手机号 public static String getMobile(){ return tl.get().getMobile(); } //清空threadlocal public static void remove(){ tl.remove(); } }