ThreadLocal

这篇博客探讨了如何在Java Web应用中实现登录拦截器,通过检查JWT令牌来验证用户登录状态。当用户请求需要登录才能访问的资源时,拦截器会检查请求头中的Authorization字段。如果令牌无效或用户信息无法从数据库获取,拦截器将返回错误响应。登录验证成功后,使用ThreadLocal存储用户信息,以便在Controller中直接获取。该方法确保了用户会话的安全和高效管理。
摘要由CSDN通过智能技术生成
import com.yyf.blogapi.po.SysUser;

public class UserThreadLocal {
    private UserThreadLocal() {
    }

    private static final ThreadLocal<SysUser> LOCAL = new ThreadLocal<>();

    public static void put(SysUser sysUser) {
        LOCAL.set(sysUser);
    }

    public static SysUser get() {
        return LOCAL.get();
    }

    public static void remove() {
        LOCAL.remove();
    }
}
package com.yyf.blogapi.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yyf.blogapi.po.SysUser;
import com.yyf.blogapi.service.ISysUserService;
import com.yyf.blogapi.util.JwtUtil;
import com.yyf.blogapi.util.UserThreadLocal;
import com.yyf.blogapi.vo.ErrorCode;
import com.yyf.blogapi.vo.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class NeedLoginInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;
    @Resource
    ISysUserService sysUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        log.info("request uri   : {}",request.getRequestURI());
        log.info("request method: {}",request.getMethod());
        log.info("token         : {}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)){
            Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }

        //验证token
        Claims claims = jwtUtil.getClaims(token);
        SysUser user = sysUserService.checkToken(token);
        if (user==null){
            Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }

        //登录验证成功,放行
        //我希望在controller中 直接获取用户的信息 怎么获取?
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}

SysUser user = UserThreadLocal.get();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值