1 package cn.itcast.cookie; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Date; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.Cookie; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class CookieDemo extends HttpServlet { 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 response.setCharacterEncoding("UF-8"); 19 response.setContentType("text/html;charset=UTF-8"); 20 21 PrintWriter out = response.getWriter(); 22 out.print("您上次访问的时间是:"); 23 24 //获得用户的时间cookie 25 Cookie cookies[] = request.getCookies(); 26 for(int i=0;cookies!=null&&i<cookies.length;i++){ 27 if(cookies[i].getName().equals("lastAccessTime")){ 28 long cookieValue = Long.parseLong(cookies[i].getValue()); 29 Date date = new Date(cookieValue); 30 31 out.print(date.toLocaleString()); 32 33 } 34 } 35 36 //给用用户会送最新的访问时间。 37 Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); 38 cookie.setMaxAge(1*30*24*3600); 39 cookie.setPath("/ServletDemo"); 40 41 response.addCookie(cookie); 42 43 } 44 45 46 public void doPost(HttpServletRequest request, HttpServletResponse response) 47 throws ServletException, IOException { 48 49 50 } 51 52 }