WEB开发网
开发学院软件开发Java JavaWeb利用cookie记录访问的时间 阅读

JavaWeb利用cookie记录访问的时间

 2012-09-13 10:21:03 来源:WEB开发网   
核心提示:package com.fenghuo.cookie;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;import javax.servlet.ServletException;import javax.servle
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);
	}
}

Tags:JavaWeb 利用 cookie

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接