流程

1:先拿到浏览器的cookies,然后判断是否为空遍历,如果cookies是上一次存的时间cookies,便向浏览器输出。
2:再次向浏览器cookie写入今天的日期

实现

代码

servlet

package visitTime;
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 visit extends HttpServlet {
private static final long serialVersionUID = 1L; 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//得到上一次的COOKIES
	//设置字符编码
	response.setContentType("text/html;charset=utf-8");
	//得到COOKIES并输出返回给浏览器
	PrintWriter out=response.getWriter();
	Cookie[] cookies=request.getCookies();
	for (int i=0;cookies !=null && i<cookies.length;i++) {
		if("visitTime".equals(cookies[i].getName())) {
			//cookiesValue转换为,date接受的LONG类型数据
			long time=Long.parseLong(cookies[i].getValue());
			//输出浏览器
			out.write("你上一次的访问时间是:"+new Date(time));
		}
	}	
	//写cookies入浏览器
	Cookie cookie=new Cookie("visitTime",System.currentTimeMillis()+"");
	//设置失效时间为1小时
	cookie.setMaxAge(60 * 60);
	//设置cookie路径
	cookie.setPath("/");
	//给浏览器添加cookies
	response.addCookie(cookie);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
}
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>LastVisitTime</display-name>
<welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
  <description></description>
  <display-name>visit</display-name>
  <servlet-name>visit</servlet-name>
  <servlet-class>visitTime.visit</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>visit</servlet-name>
  <url-pattern>/visit</url-pattern>
</servlet-mapping>
</web-app>