使用cookie显示用户访问时间,黑马程序员教材案例

问题描述

我使用的教材是黑马程序员编著的《Java Web程序设计任务教程》,版本为2017年1月第1版
今天依旧像往常一样敲着书上的案例,147页案例–使用Cookie显示用户上次访问时间
发现了一个很恶心的问题
我照着书上的代码敲完之后,运行发现我的结果与书上的并不一样
附上我的源码

public class lastAccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String lastAccess = null;
        Cookie[] cookies = req.getCookies();
        System.out.println(cookies.length);
        for (Cookie cookie : cookies) {
//            如果Cookie的名称为“lastAccess",则获取该Cookie值
            if("lastAccess".equals(cookie.getName())){
                lastAccess = cookie.getValue();
                break;
            }
        }
//        判断是否存在名称为lastAccess的cookie
        System.out.println(lastAccess);
        if(lastAccess == null){
            resp.getWriter().print("您是首次访问本网站");
        }else {
            resp.getWriter().print("您上次访问的时间是" + lastAccess);
        }
//        创建cookie,将当前时间作为cookie的值发送给客户端
        String currentTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccess",currentTime);
//        发送cookie
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

按照正常的运行结果应该是这样的

第一次访问页面应该是这样的
在这里插入图片描述
刷新应该是这样的
在这里插入图片描述

我的结果

无论怎么刷新,结果都是这个
在这里插入图片描述
困扰了我一整天,反复排查自己的代码,并没有错误。
于是我去网上搜,发现并没有人遇到我这样的情况
无意间看到某一篇文章中说道,Tomcat不同版本对时间格式要求是不同的
我的本地Tomcat版本是9.0,然后我就去下载了8.5版本,发现解决不了问题;
然后继续追溯,下载8.0版本,问题解决了!
Tomcat8.0可以正常运行教材上的代码

解决方案

Tomcat8.5及以后版本对yyyy-MM-dd hh:mm:ss时间格式的支持是抽风的,
Tomcat8.0及以前版本是对此格式支持完美的!建议小伙伴下载Tomcat8.0进行学习。

posted @ 2022-11-13 22:27  秋天Code  阅读(55)  评论(0)    收藏  举报