Cookie显示上次访问时间出现错误的问题

public class LastAccessServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 中文乱码
        response.setContentType("text/html;charset=utf-8");
        // 1.获取所有cookie
        Cookie[] cookies = request.getCookies();
        // 遍历cookie数组
        String lastTime = null;
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            // 获取cookie的名称
            String name = cookies[i].getName();
            if ("lastAccess".equals(name)) {
                // 获取cookie的时间
                lastTime = cookies[i].getValue();
            }
        }
        if (lastTime == null) {
            // 第一次访问
            response.getWriter().print("你是第一次访问");

        } else {
            // 不是第一次访问,把上次访问时间写回到浏览器
            response.getWriter().print("你的上次访问时间:" + lastTime);

        }
        // 第三次 第四次
//        String time = String.format("%tF %<tT", new Date());

        Cookie cookie = new Cookie("lastAccess", System.currentTimeMillis() + "");
        cookie.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(cookie);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

 在浏览器进行访问总是显示第一次访问,打开F12一看状态码为500;看到一篇帖子说

cookievalue

后来更改了Date获取的参数类型就能运行了。

博客参考:https://blog.csdn.net/qq_41855420/article/details/101936262

原文地址:https://www.cnblogs.com/springa/p/12746421.html