JavaWeb-Cookie-16课-2023-04-06

package com.feijian.servlet;

import javax.servlet.ServletException;
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.io.PrintWriter;
import java.util.Date;

public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        //从客户端获取Cookie
        Cookie[] cookies = req.getCookies();
        //判断Cookie是否存在
        if (cookies!=null){
            writer.print("<h1>你上一次访问的时间是:</h1>");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie=cookies[i];
                if (cookie.getName().equals("lastLoginTime")){
                    //获取Cookie的值
                    String date = cookie.getValue();
                    long lastLoginTime = Long.parseLong(date);
                    Date date1 = new Date(lastLoginTime);
                    writer.print(date1.toLocaleString());
                }
            }
        } else {
            System.out.println("这是你第一次访问");
        }
        //服务器给客户端响应一个cookie
        Cookie lastLoginTime = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        //设置有效时间
        lastLoginTime.setMaxAge(24*60*60);
        resp.addCookie(lastLoginTime);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
posted @ 2023-04-06 20:05  Rui2022  阅读(8)  评论(0编辑  收藏  举报