ThreadLocal 每个用户保存一个信息

package e.itr.context;

import e.itr.entity.User;
import e.itr.exception.BadRequestException;

public class AppContext {
    private static ThreadLocal currentUserHolder = new ThreadLocal<>();

    private static void setCurrentUser(User user) {
        currentUserHolder.set(user);
    }

    public static User getCurrentUser() {
        return currentUserHolder.get();
    }

    public static void clearAll() {
        currentUserHolder.remove();
    }

    /**
     * 注意 千万不要注释此代码,涉及安全性相关
     */
    public static void checkAndminRole() {
        User currentUser = AppContext.getCurrentUser();
        if (currentUser == null) {
            throw new BadRequestException("无权限访问此资源");
        }
        if (!"superadmin".equals(currentUser.getRoleId())) {
            throw new BadRequestException("无权限访问此资源");
        }
    }
}

 

 Method m = AppContext.class.getDeclaredMethod("setCurrentUser", User.class);
                m.setAccessible(true);
                m.invoke(null, token);
   User u = AppContext.getCurrentUser();
        String userAgentId = u.getUserAgentId();

 

你可能感兴趣的:(JAVA)