当前位置: 代码迷 >> Web前端 >> 《JavaWeb-利用cookie记要访问的时间》
  详细解决方案

《JavaWeb-利用cookie记要访问的时间》

热度:477   发布时间:2012-09-18 16:21:42.0
《JavaWeb---利用cookie记录访问的时间》
package com.fenghuo.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyCookie extends HttpServlet {

	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();//得到response输出流
		out.print("<a href='/myweb/servlet/ClearCookie'>清除上次访问时间</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")){
			
				//判断如果是我们想要的cookie取出其中的值
				long cookieValue = Long.parseLong(cookies[i].getValue());
				
				//将数据封装成Date对象
				Date date = new Date(cookieValue);
				//以我们中国时间格式写到response流中,以便服务器写给浏览器
				out.print(date.toLocaleString());
			}
		}
		//给用户回送最新访问时间
		//如果两个cookie的名字,MaxAge,Path相同后者会覆盖前者
		Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
		cookie.setMaxAge(1*30*24*3600);
		cookie.setPath("/myweb");
		
		//将定义好的cookie加到response对象中
		response.addCookie(cookie);
	}

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

		doGet(request, response);
	}

}
package com.fenghuo.cookie;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClearCookie extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//定义一个相同的cookie将MaxAge(cookie有效时间)设为0
		Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
		cookie.setMaxAge(0);
		cookie.setPath("/myweb");
		response.addCookie(cookie);
		
		//重定向到MyCookie的Servlet中,刷新数据
		response.sendRedirect("/myweb/servlet/MyCookie");
	}

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

		doGet(request, response);
	}
}


  相关解决方案