cookie案例:记录上次访问时间

cookie应用案例:基于Tomcat实现用cookie来记录上次访问页面的时间

@WebServlet("/Servletcookie")//确定访问页面的路径
public class Servletcookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);//在使用post请求时也转到本类中的doget方法
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        boolean flag = true;//标志变量
        Cookie[] cookies = request.getCookies();//获得cookie对象数组

        if (cookies !=null && cookies.length>0){//保证cookie不为空
            for (Cookie cookie :cookies){
                String name = cookie.getName();
                if ("lastTime".equals(name)){//如果cookie中有lastTime数据
                    flag = false;//如果cookie中有lastTime则修改标志变量
                    String value = cookie.getValue();//获得上次访问的时间
					/*因为在日期的字符串中有中文字符和特殊符号虽然Tomcat8之后已经支持中文字符但如果出现特殊符号还是需要进行解码和转码操作*/
                    value = URLDecoder.decode(value,"utf-8");//对value解码操作
                    System.out.println("第二次访问解码前:"+value);
                    response.getWriter().write("欢迎回来,您上次访问的时间是:"+value);
                    System.out.println("第二次访问解码后:"+value);


                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);//得到当前时间的字符串格式
                    cookie.setMaxAge(60*60*24*30);//设置cookie在浏览器的存在时间
                    System.out.println("第二次访问编码前:"+str_date);
                    str_date = URLEncoder.encode(str_date,"utf-8");//对str-dat
                    System.out.println("第二次访问编码前:"+str_date);
                    cookie.setValue(str_date);
                    response.addCookie(cookie);//将当前访问的 时间设置到rookie中
                    break;
                }
            }
        }
        
        /*第一次访问没有lastTime所以flag为true*/
        if (flag){//flag标志来判断cookie中是否有lasttime
            Date date = new Date();//创建时间对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            System.out.println("第一次访问编码前:"+str_date);
            str_date = URLEncoder.encode(str_date,"utf-8");//对strdate以utf8进行编码
            System.out.println("第一次访问编码后:"+str_date);
            Cookie cookie = new Cookie("lastTime",str_date);
            response.addCookie(cookie);
            response.getWriter().write("欢迎访问!这是您第一次访问!");

        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值