cookie实现记住上一次访问时间

     httpServletResponse.setCharacterEncoding("UTF-8");

        httpServletResponse.setContentType("application/json;charset=UTF-8");

        boolean flag=false;
    //获取所有cookie
        Cookie[] cookies = httpServletRequest.getCookies();
    //存在cookie值的处理
        if (cookies != null&&cookies.length > 0) {
            for (Cookie cookie : cookies) {
//                获取cookie的名称
                String name = cookie.getName();
                if ("lastTime".equals(name)) {
                    flag = true;
//                    设置cookie的value
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String format = simpleDateFormat.format(new Date());
//                    URL编码
                    format = URLEncoder.encode(format, StandardCharsets.UTF_8);
//                    获得cookie的值
                    String value = cookie.getValue();
//                    设置cookie的值
                    cookie.setValue(format);
//                    设置cookie的最大存储时间
                    cookie.setMaxAge(60 * 60 * 24 * 30);
//                  将cookie添加到响应中
                    httpServletResponse.addCookie(cookie);
//                    URL解码
                    value = URLDecoder.decode(value, StandardCharsets.UTF_8);
                    httpServletResponse.getWriter().
                            write(Objects.requireNonNull(JsonUtils.obiectToJson(success("欢迎回来,您上次访问时间为:" + value))));
                    }
            }
        }
//不存在cookie值的处理
        if (cookies==null||cookies.length == 0|| !flag){
            //                    设置cookie的value
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            //                    URL编码
            format= URLEncoder.encode(format, StandardCharsets.UTF_8);
            Cookie cookie = new Cookie("lastTime",format);
//                    设置cookie的最大存储时间
            cookie.setMaxAge(60*60*24*30);
//                  将cookie添加到响应中
            httpServletResponse.addCookie(cookie);
            httpServletResponse.getWriter().
                    write(Objects.requireNonNull(JsonUtils.obiectToJson(success("欢迎首次访问!"))));

        }

猜你喜欢

转载自blog.csdn.net/weixin_43897590/article/details/107712978