java_Cookie_example(你上次访问的时间)

时间:2021-08-20 18:59:26
	public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
out.print("你上次访问时间是: "); // 获得用户的时间cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("lastAccessTime")) {
long cookieValue = Long.parseLong(cookies[i].getValue());// 用户上次访问时间
Date date = new Date(cookieValue);
out.print(date.toLocaleString());
}
} //给用户回送最新的访问时间
Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
cookie.setMaxAge(1*30*24*3600);
cookie.setPath("/Test"); response.addCookie(cookie); }