ThreadLocal的使用

AuthHolder
public class AuthHolder {

    private static final ThreadLocal<User> threadLocal = new ThreadLocal<>();

    public static Optional<User> getUser(){
        return Optional.fromNullable(threadLocal.get());
    }

    public static boolean hasLogin(){
        User user= threadLocal.get();
        return null!=user;
    }

    public static void setUser(User user){
        threadLocal.set(user);
    }


    public static Optional<Long> getUserId(){
        User user= threadLocal.get();
        if(null == user|| null == user.getId()){
            return Optional.absent();
        }
        return Optional.fromNullable(user.getId().longValue());
    }

    public static Optional<String> getUserName() {
        User user = threadLocal.get();
        if (null == user) {
            return Optional.absent();
        }
        return Optional.fromNullable(user.getName());
    }
}

登录拦截器添加:

if(userRole.getType()<=functionRole.getType()){
    AuthHolder.setUser(SessionUtils.getUser(httpServletRequest.getSession()));
    return true;
}else {
    httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
    P.throwMessageExceptionIf(true,HttpStatus.FORBIDDEN.value(),"没有权限访问");
    return false;
}

在后续逻辑即可使用

@Override
@Transactional
public Long saveInfo(LocationRequest locationRequest) {
    checkLocationRequest(locationRequest);
    List<Location> locationList = locationService.getByDisName(locationRequest.getAppId(), locationRequest.getDisName());
    if (CollectionUtils.isNotEmpty(locationList)) {
        P.throwMessageExceptionIf(true, 200, "位置的描述名已经存在,请修改描述名称");
    }
    Location location = locationRequest.toLocation(locationRequest);
    Long id = locationService.save(location,AuthHolder.getUserId().get(), AuthHolder.getUserName().get());
    return id;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值