1. 程式人生 > >cookie獲取瀏覽器上次訪問時間

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 RemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//設定編碼
		response.setContentType("text/html;charset=utf-8");
		PrintWriter w=response.getWriter();
		//獲取指定名稱的cookie    lastTime  當前時間
		Cookie[] cookies=request.getCookies();
		Cookie c=getCookieByName("lastTime",cookies);
		//判斷是否為空
		if(c==null){
			//cookie為空  提示:第一次訪問
			w.println("您是第一次訪問,歡迎光臨");
		}else{
			//cookie不為空  獲取value 展示上一次訪問的時間
			String value=c.getValue();
			long time=Long.parseLong(value);
			Date date=new Date(time);
			w.println("您上一次訪問的時間:"+date.toLocaleString());
		}
		//將當前訪問時間記錄  建立cookie
		c=new Cookie("lastTime",new Date().getTime()+"");
		//持久化
		c.setMaxAge(3600);
		//設定路徑
		c.setPath(request.getContextPath()+"/");
		//寫回瀏覽器
		response.addCookie(c);
	}

	private Cookie getCookieByName(String name, Cookie[] cookies) {
		if(cookies!=null){
			for(Cookie c:cookies){
				if(name.equals(c.getName())){
					return c;
				}
			}
		}
		return null;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}