Cookie记录访问网站的时间

Cookie记录访问网站的时间

1.Cookie
  @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");//设置编码格式
        resp.setContentType("Text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies(); //Cookie存在多个 是否存在  创建Cookie
        if(cookies!=null){
            out.write("上一次访问时间是:");
            for(int i =0;i<cookies.length;i++){
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("lastLoginTime")){  //获取Cookie
                  Long lastLoginTime= Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);//打印访问时间
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("第一次访问");
        }
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        resp.addCookie(cookie);

}

2.配置web.xml
 <servlet>
    <servlet-name>image</servlet-name>
    <servlet-class>com.ws.Servlet.testyanzhengma</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>image</servlet-name>
    <url-pattern>/image</url-pattern>
  </servlet-mapping>
3.记得导入依赖
  <dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    <scope>provided</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
  </dependency>
</dependencies>
4.测试内容
  • 需要访问两次cookies
  • 第一次时记录时间 第二次才能打印出来上一次的时间

测试结果
在这里插入图片描述

Cookie是存放在客户端的浏览器上面,在本地可以查看。

5.来源
1.使用的TomCat9.0.62版本
2.来自狂神视频的学习
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值