手把手教你cookie实现页面显示上次访问时间功能

1.代码分析

package cn.bytedance.showtime;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 这是靓仔呀
 * @Date: 2020/12/04/10:53 下午
 * @Description: a demo for showing time
 */

@WebServlet("/TimeTeller")
public class TimeTeller extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置contentType编码,获得cookies对象
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = req.getCookies();
        //定义标识位,作用:自己看代码悟
        boolean flag = true;
        if (cookies != null && cookies.length != 0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("lastTime".equals(name)){
                    flag = false;
                    //获取lastTime的value值,URLDecoder解码后显示在页面上
                    String value = cookie.getValue();
                    System.out.println("解码前:"+value);
                    value = URLDecoder.decode(value,"utf-8");
                    System.out.println("解码后:"+value);
                    resp.getWriter().println("<h4>欢迎回来,你上次访问时间是:</h4>"+value);

                    //修改cookie的新值
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = simpleDateFormat.format(new Date());
                    System.out.println("编码前:"+str_date);
                    str_date = URLEncoder.encode(str_date, "utf-8");
                    System.out.println("编码后:"+str_date);
                    //修改cookie的值和生命周期,发送cookie
                    cookie.setValue(str_date);
                    cookie.setMaxAge(60*60*24);
                    resp.addCookie(cookie);

                }
            }
        }

        if (cookies == null || cookies.length ==0 || flag){
            resp.getWriter().println("当前你是首次访问页面..");
            //创建cookie对象,并且将cookie保存到客户端
            Cookie cookie = new Cookie("lastTime","");
            //时间格式化
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = simpleDateFormat.format(new Date());

            System.out.println("编码前:"+str_date);
            //对str进行URLEncoder编码,因为cookie的value不可以有特殊字符,比如空格
            str_date = URLEncoder.encode(str_date, "utf-8");
            System.out.println("编码后:"+str_date);
            //修改cookie的值和生命周期,发送cookie
            cookie.setValue(str_date);
            cookie.setMaxAge(60*60*24);
            resp.addCookie(cookie);
        }
    }

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



2.效果展示
a.第一次访问页面时
cookie实现页面显示上次访问时间示意图1
b.刷新后
cookie实现页面显示上次访问时间示意图1
c.在浏览器中查看cookie信息
cookie实现页面显示上次访问时间示意图3