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);
}
}
网友评论