使用ThreadLocal獲取登錄者的信息


1.工具類(定義ThreadLocal)

public class UserThreadLocal {
    
    private static ThreadLocal<User> userThread = new ThreadLocal<>();
    
    public static void set(User user){
        
        userThread.set(user);
    }
    
    public static User get(){
        
        return userThread.get();
    }
    
    //防止內存泄漏
    public static void remove(){
        
        userThread.remove();
    }
    
}

2.在攔截器中獲取用戶信息,並存入ThreadLocal中

//定義用戶攔截器
public class UserInterceptor implements HandlerInterceptor{
    
    @Autowired
    private JedisCluster jedisCluster;
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //1.獲取Cookiez中的token
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("JT_TICKET".equals(cookie.getName())){
                token = cookie.getValue();
                break;
            }
        }
        
        //2.判斷token是否有數據
        if(token != null){
            //2.1判斷redis集群中是否有數據
            String userJSON = jedisCluster.get(token);
            if(userJSON != null){
 User user = objectMapper.readValue(userJSON,User.class);
                //將user數據保存到ThreadLocal中
                UserThreadLocal.set(user);
                //證明用戶已經登陸 予以放行
                return true;
            }
        }
        
        //配置重定向
        response.sendRedirect("/user/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
    }

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

3.在controller層中獲取用戶信息,並將信息移出ThreadLocal

    /*
     * 1.實現訂單確認頁面的跳轉
     * url: /order/create.html 
     */
    @RequestMapping("/create")
    public String create(Model model){
 Long userId = UserThreadLocal.get().getId();
        //根據userId查詢購物車信息
        List<Cart> cartList = cartService.findCartByUserId(userId);
 UserThreadLocal.remove();
        model.addAttribute("carts", cartList);
        return "order-cart";
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM