Cookie 实现记住上一次访问时间

最近看以往的知识点时,稍微整理了下,下面是Cookie 实现记住上一次访问时间

见代码:

1)CookieServlet

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;

@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        System.out.println("CookieServlet被访问了......");
        response.setContentType("text/html;charset=utf-8");
        boolean isCookie=false;
        // 先判断cookie 是否有值
        Cookie[] cookies = request.getCookies();
        if(cookies!=null &&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if("lastTime".equals(name)){
                    isCookie=true;
                    // 有上次的访问时间
                    Date date=new Date();
                    SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = format.format(date);
                    System.out.println("解码前  日期为:"+str_date);
                    str_date=URLEncoder.encode(str_date,"utf-8");
                    System.out.println("编码后日期为:"+str_date);

                    String value = cookie.getValue();
                    System.out.println("解码前日期为:"+value);
                    value=URLDecoder.decode(value,"utf-8");
                    System.out.println("解码后日期为:"+value);
                    cookie.setValue(str_date);
                    response.addCookie(cookie);
                    response.getWriter().write("<h1>欢迎回来,您上次登陆的时间为"+value+"</h1>");


                }
            }
        }

        if(cookies==null ||  isCookie==false || cookies.length==0){
            System.out.println("第一次访问。。。。");
            // 第一次访问
            Date date=new Date();
            SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = format.format(date);
            System.out.println("第一次访问 解码前日期为:"+str_date);
            String str_date2=URLEncoder.encode(str_date,"utf-8");
            System.out.println("第一次访问,解码后日期为:"+str_date);
            Cookie cookie=new Cookie("lastTime",str_date2);
            response.addCookie(cookie);
            response.getWriter().write("<h1>欢迎你第一次访问,本次的访问时间为"+str_date+"</h1>");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}

2)直接访问即可 ,见下图:

猜你喜欢

转载自blog.csdn.net/huangshun9541/article/details/88145597