1 案例分析
2 Java实现代码
1 public class LastAccessTimeServlet extends HttpServlet { 2 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { 3 4 //Response 乱码问题的解决 5 response.setContentType("text/html;charset=UTF-8"); 6 7 //获得当前时间 8 Date date=new Date(); 9 SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 10 String currentTime=format.format(date); 11 12 //1 创建cookie记录最新的当前访问时间 13 Cookie cookie=new Cookie("lastAccessTime", currentTime); 14 cookie.setMaxAge(60*60); 15 response.addCookie(cookie); 16 //2 获得客户端携带的cookie----lastAccessTime 17 String lastAccessTime=null; 18 Cookie[] cookies=request.getCookies(); 19 if(cookies!=null){ 20 for (Cookie coo : cookies) { 21 if ("lastAccessTime".equals(coo.getName())) { 22 lastAccessTime=coo.getValue(); 23 } 24 } 25 } 26 //3判断是第几次访问 27 if (lastAccessTime==null) { 28 response.getWriter().write("您是第一次访问"); 29 } else { 30 response.getWriter().write("您上次访问时间是:"+lastAccessTime); 31 } 32 } 33 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception { 34 doGet(request, response); 35 } 36 }