02-cookie案例-显示用户上次访问网站的时间
javax.servlet.http.Cookie类用于创建一个Cookie,
response接口也中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。
同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。Cookie类的方法:
response接口也中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。
同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。Cookie类的方法:
- public Cookie(String name,String value)
- setValue与getValue方法
- setMaxAge与getMaxAge方法
- setPath与getPath方法
- setDomain与getDomain方法
- getName方法
-
public class CookieDemo2 extends HttpServlet { private static final long serialVersionUID = 1L; //02-cookie案例-显示用户上次访问网站的时间 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("您上次访问的时间是:"); //获得用户的时间cookie Cookie cookies[] = request.getCookies(); for(int i = 0;cookies != null && i < cookies.length;i++){ if(cookies[i].getName().equals("lastAccessTime")){ long cookieValue = Long.parseLong(cookies[i].getValue()); Date date = new Date(cookieValue); out.print(date.toLocaleString()); } } //给客户送回最新的访问时间 Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(3600);//设置cookie的时间 cookie.setPath("/day07");//设置给客户端返回cookie的目录 response.addCookie(cookie); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }