Cookie creates temporary user

Business logic

The offline shopping cart (the user is not logged in) transfers data through cookies. Create a UserInfo (user id, user-key value, whether it is a temporary user) to save user information. User information is obtained before sending a request to the Controller. Information is provided to the Controller layer to call

  1. Determine whether the user is logged in. If the user is logged in, set the user id to UserInfo
  2. Check if there is a cookie named user-key. If so, set it to UserInfo. If not, create one yourself. The user-key in the cookie represents a temporary user.
  3. Finally, put the UserInfo in the local thread and provide it to the subsequent postHandle() call.
  4. If the temporary user flag in UserInfo is not set to true, it means that there is no temporary user (user-key), save a temporary user cookie in the browser

ThreadLocal

Tomcat will open a thread for each request and execute the current request until the end.
For example: interceptor -> controller -> service -> dao are all the same thread.

Interceptor

It is equivalent to adding a layer of if judgment before my Controller request. Here is to judge whether there is a temporary user and process it
(1) Custom interceptor rules

/**
 * 购物车拦截器
 */
public class CartIntercept implements HandlerInterceptor {
    
    

    /**
     * preHandle放行 -> controller(购物车请求) ->
     */


    /**
     *  tomcat会开一个线程,执行当前请求 直到结束
     * 拦截器 ->  controller -> service -> dao 都是同一线程
     * 在执行目标方法之前,判断用户的登录状态.并封装传递给controller目标请求
     */
    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

    /***
     * 目标方法执行之前
     *
     * 1.判断用户是否登陆,如果用户已登陆,则set 用户id
     * 2.只有登陆了才会设置userId,user-key有就从cookie中取,没有就自己创建set一个uuid
     * 3.看cookie中有没有name叫user-key的,有就set到UserInfo,没有就自己创建一个临时用户
     * 4.最后把UserInfo放到本地线程,提供给
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    

        /**
         *  cookie
         *
         *  user-key(代表临时用户)     xxxxxx
         */
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        //获得当前登录用户的信息
        MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(AuthServiceConstant.LOGIN_USER);


        /**
         * 只有登陆了才会设置userId,user-key有就从cookie中取,没有就自己创建set一个uuid
         */
        if (memberResponseVo != null) {
    
    
            //用户登录了
            userInfoTo.setUserId(memberResponseVo.getId());
        }

        /**
         * 看cookie中有没有user-key,有就set到UserInfo,没有就自己创建一个临时用户
         */
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
    
    
            for (Cookie cookie : cookies) {
    
    
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
    
    
                    userInfoTo.setUserKey(cookie.getValue());
                    //标记为已是临时用户
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //如果没有临时用户一定分配一个临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
    
    
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        //目标方法执行之前
        toThreadLocal.set(userInfoTo);

        //全部放行
        return true;
    }


    /**
     * 业务执行之后,浏览器保存cookie的临时用户
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    

        //获取当前用户的值
        UserInfoTo userInfoTo = toThreadLocal.get();

        //如果有临时用户信息就不用去设置cookie
        if (!userInfoTo.getTempUser()) {
    
    
            //创建一个cookie
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            //扩大作用域
            cookie.setDomain("gulimall.com");
            //设置过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

    }


}

(2) Put the interceptor into the container

@Configuration
public class GulimallWebConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new CartIntercept())//注册拦截器
                .addPathPatterns("/**");
    }
}

Guess you like

Origin blog.csdn.net/weixin_44847885/article/details/131424773