1. 程式人生 > >從Cookie獲取上次訪問時間簡單示例

從Cookie獲取上次訪問時間簡單示例

1.程式碼編寫

CookieAndLastVisitTime.java

package org.csdn.gyt;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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


/**
 * Servlet implementation class CookieAndLastAccessTime
 */
@WebServlet("/CookieAndLastVisitTime")
public class CookieAndLastVisitTime extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieAndLastVisitTime() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html;charset=utf-8");
		String lastVistiTime = null;
		// 獲取Cooikes
		Cookie[] cookies = request.getCookies();
		// 判斷cookies是否符合條件
		for (int i=0; cookies != null && i < cookies.length; i++) {
			if ("lastVisit".equals(cookies[i].getName())) {
				lastVistiTime = cookies[i].getValue();
				break;
			}
		}
		// 判斷是否為初次訪問
		if (lastVistiTime == null) {
			response.getWriter().println("Welcome, you are visiting our website for the first time.");
		} else {
			response.getWriter().println("Welcome, your last visit is " + lastVistiTime);
		}
		// 設定本次訪問的時間
		Cookie cookie = new Cookie("lastVisit", new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss").format(new Date()));
		// Cookie存活時間30s
		cookie.setMaxAge(30);
		response.addCookie(cookie);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

開啟伺服器:
瀏覽器訪問:
在這裡插入圖片描述

30s內重新整理頁面:
在這裡插入圖片描述

完!