欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Java】【cookie和session】Cookie

程序员文章站 2022-03-11 16:39:49
...
package com.stu.demo;

import jericho.tools.MyDatetime;

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.io.PrintWriter;

@WebServlet(name = "Demo")
public class Demo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    
    if (request.getParameter("type").equals("clear")) {
    //      清除cookie
        Cookie cookie = new Cookie("lastAccessTime","");
        cookie.setPath("/");
        cookie.setMaxAge(0); // 设置保存时间为0视为清除
        response.addCookie(cookie);
    }else{
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length && cookies[i] != null; i++) {
            if (cookies[i].getName().equals("lastAccessTime")) {
                out.println("上次访问时间:" + new MyDatetime(cookies[i].getValue()).get());
            } else {
    //          记录访问时间
                out.println("第一次访问");
            }
        }
        Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(720 * 3600); // 设置保存时间则保存到硬盘上,不设置则保存到浏览器内存中
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}

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