String字符串不相等判断问题
equals比较的是具体值,而==或 != 比较的是地址值
这样去使用

if(!user.getPassword().equals(password))

不要只写 isEmpty,如果 token为 null,会报空指针异常。

String token = request.getHeader("token");
if(token == null || token.isEmpty()){        // token 是否为空

校验 token

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;    // 静态资源直接放行
        }
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()){        // token 是否为空
            System.out.println(token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessException(Code.ACCESS_ERR,"未登录,无权访问");
        }else{
            try {
                jwtUtils.VerifyToken(token);
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                String res = ops.get(token);
                if(res == null || res.isEmpty()){
                    throw new BusinessException(Code.ACCESS_ERR,"token已过期");
                }else{
                    redisTemplate.expire(token,30, TimeUnit.MINUTES);
                    return true;
                }
            }catch(MalformedJwtException ex){
                throw new BusinessException(Code.ACCESS_ERR,"token 格式不对",ex);
            }catch(SignatureException ex){
                throw new BusinessException(Code.ACCESS_ERR,"token 不对",ex);
            }catch(ExpiredJwtException ex){
                throw new BusinessException(Code.ACCESS_ERR,"token已过期",ex);
            }
        }
    }
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐