java_Cookie添加和删除

 

	public 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("<a href='/Test/servlet/CookieTest2'>清除上次访问时间</a><br/>");
		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(1*30*24*3600);
		cookie.setPath("/Test");
		
		response.addCookie(cookie);
	}


//删除

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
		cookie.setMaxAge(0);
		cookie.setPath("/Test");
		response.addCookie(cookie);
		response.sendRedirect("/Test/servlet/CookieTest1");
	}


 

 

posted @ 2013-12-10 00:21  MrMrCash  阅读(224)  评论(0编辑  收藏  举报