cookie 关于记录上次访问时间的servlet

public class LastTime extends HttpServlet {
     
      public void doGet (HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
         //格式化字符集
              response.setContentType("text/html;charset=utf-8");
         //制作当前时间字符串
              SimpleDateFormat sdf= new SimpleDateFormat("yyyy年MM月dd天hh时mm分ss秒");
              String curDate =sdf.format( new Date());
              
              //获取cookie
              Cookie[] cookies=request.getCookies();
              String lastTime= null ;
               if (cookies!= null ){
                   for (Cookie cookie:cookies)//对所有的cookie遍历
                  {
                        if (cookie.getName().equals("LastTime"))
                       {
                       lastTime=cookie.getValue();
                       lastTime=URLDecoder. decode (lastTime,"utf-8");
                       response.getWriter().write("欢迎再次光临,你上次访问的时间为:"+lastTime+"</br>现在的时间为:"+curDate);
                       curDate=URLEncoder. encode (curDate,"utf-8");
                       cookie.setValue(curDate);
                       response.addCookie(cookie);
                        break ;
                       }
                  }
              }
               if (cookies== null ||lastTime== null )
              {
                  //在浏览器显示
                  response.getWriter().write("你是第一次来到本网站,当前时间为:"+curDate);
                  //对字符串加密
                   curDate=URLEncoder. encode (curDate,"utf-8");
                  //把当前时间保存在cookie中
                  Cookie c= new Cookie("LastTime", curDate);
                  
                  //把cookie发送到浏览器
                  response.addCookie(c);
                  
              }
     }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值