1 package cn.gs.ly.servlet; 2 import java.io.IOException; 3 import java.io.PrintWriter; 4 import java.util.Date; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.Cookie; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 public class LastVisitTimeServlet extends HttpServlet { 13 @Override 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 resp.setContentType("text/html; charset=UTF-8"); 16 17 PrintWriter out = resp.getWriter(); 18 out.print("您上次访问的时间是:"); 19 //先获取cookie 再赋值 20 Cookie [] co = req.getCookies();//所有 Cookie 对象的数组 21 for(int i=0;co!=null&&i<co.length;i++){ //遍历cookie数组 22 if("last_time".equals(co[i].getName())){//获取cookie名 23 String value = co[i].getValue(); //获取cookie值 24 long time = Long.parseLong(value); //转换cookie值类型 25 out.println(new Date(time).toLocaleString());//显示cookie里的最后一次系统时间 26 } 27 } 28 29 //先查看cookie的最后时间并显示。再获取现在系统当前时间 30 long time = System.currentTimeMillis(); 31 Cookie c = new Cookie("last_time",time+"");//构造带指定名称和值的 cookie。 32 c.setMaxAge(30*24*60*60);//cookie存活时间 33 c.setPath(req.getContextPath()); //在当前应用有效 s.setPath("/"); 34 resp.addCookie(c);//添加cookie 35 } 36 @Override 37 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 38 this.doPost(req, resp); 39 } 40 }