简单的Cooki案例——记录用户上次访问该网页的时间

时间:2023-03-08 17:59:57

功能:

帮助网站实现提示客户端计算机上次访问网站的时间

实现原理:

将每一个会话作为一次访问过程,将每次会话的开始时间作为每次访问网站的时间,然后将这个时间以Cookie的形式存储到客户端的计算机中,客户端进行下次访问时通过该Cookie回传上次访问站点的时间值。

<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: root
Date: 2017/11/20 0020
Time: 16:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//记录用户上次访问该页面的时间
Cookie[] cookies = request.getCookies();
Cookie timeCookie = null;
if(cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
String cookieName = cookie.getName();
if (cookieName.equals("time")) {
timeCookie = cookie;
}
}
}
if(timeCookie != null){
String value = timeCookie.getValue();
response.getWriter().print("用户上次访问该网页的时间是: " + value);
}else {
response.getWriter().print("用户第一次访问该网页");
}
timeCookie = new Cookie("time",(new Date()).toString()); timeCookie.setMaxAge(999999); response.addCookie(timeCookie); %>
</body>
</html>