package com.itheima;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write("上次访问的时间是:");
//获取上次访问的时间
Cookie[] cookies = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
System.out.println(cookies[i].getName());
if(cookies[i].getName().equals("lastAccessTime")){
long date = Long.parseLong(cookies[i].getValue());
Date d = new Date(date);
pw.write(d.toLocaleString());
}
}
//把cookies写到浏览器中去
Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
cookie.setMaxAge(30*24*3600);
response.addCookie(cookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Cookie纪录上次访问时间
最新推荐文章于 2022-09-07 19:05:14 发布