记录用户上次访问时间(cookie和session)

记录用户上次访问时间(cookie和session)_第1张图片记录用户上次访问时间(cookie和session)_第2张图片记录用户上次访问时间(cookie和session)_第3张图片记录用户上次访问时间(cookie和session)_第4张图片

package javapack;

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;

import utils.cookieutils;

public class countservlet extends HttpServlet {

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 * 显示登录成功的用户个数
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		int count=(Integer) this.getServletContext().getAttribute("count");
		//获得从浏览器带来的所有cookies
		Cookie[] cookies = request.getCookies();
		//从数组中查找指定名称的cookie
		Cookie cookie = cookieutils.findcookie(cookies, "lastvisit");
		//创建一个cookie的对象
		Cookie cook =new Cookie("lastvisit", ""+System.currentTimeMillis());//获取当前时间存入cookie中
		/*cook.setPath("/J2EE");//设置cookie的有效路径
		cook.setMaxAge(3600);//设置cookie的有效时间,以s为单位
		 */		response.addCookie(cook);//保存到浏览器端
		 if(cookie==null){
			 //第一次访问
			 response.getWriter().println("

您是第"+count+"位登录成功的用户

"); }else{ long l=Long.parseLong(cookie.getValue());//将string转换成long Date d=new Date(l); response.getWriter().println("

您是第"+count+"位登录成功的用户

"+"您上次访问时间为"+d.toLocaleString()); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);//post方式和get方式执行同一方法 } }

package utils;


import javax.servlet.http.Cookie;


public class cookieutils {
public static Cookie findcookie(Cookie[] cookies,String name){
	if(cookies==null){
		return null;
	}
	else{
		for(Cookie cookie:cookies){
			if(name.equals(cookie.getName())){
				return cookie;
			}
			
		}
		return null;
	}
}
}

记录用户上次访问时间(cookie和session)_第5张图片

你可能感兴趣的:(记录用户上次访问时间(cookie和session))