1. 程式人生 > >Cookie案例-記錄使用者上次訪問的時間+商品的瀏覽記錄

Cookie案例-記錄使用者上次訪問的時間+商品的瀏覽記錄

使用cookie來記錄使用者上次訪問瀏覽器的時間

cookie工具類:從cookie陣列中獲取指定名稱的cookie

package com.utils;

import javax.servlet.http.Cookie;

public class MyCookieUtil {
	public static Cookie getCookieByName(Cookie[] cookies,String name){
		if(cookies==null){
			return null;
		}else{
			for (Cookie c : cookies) {
				if(name.equals(c.getName())==true)
					return c;
			}
			return null;
		}
	}
}

訪問的servlet

package com.servlet;

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;

import com.utils.MyCookieUtil;
/**
 * 顯示使用者上次訪問的時間
 * @author 58351
 *
 */
@WebServlet("/lasttime")
public class LastTimeServlet 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");
		
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sDate = sdf.format(date);
		/*
		 * 1、先判斷是否是第一次訪問servlet,第一次和第n次處理的業務是不一樣的
		 * 2、如果是第一次訪問,向客戶端輸出一句歡迎,並且記錄當前的時間,儲存到cookie中,回寫到瀏覽器
		 * 3、如果不是第一次訪問,獲取cookie中的值(上次的訪問時間),把時間輸出到頁面上,並且記錄到當前的時間,儲存到cookie中,回寫到瀏覽器
		 */
		//判斷是否是第一次訪問
		//獲取cookie的陣列
		Cookie[] cookies = request.getCookies();
		//查詢自己定義的cookie,查詢指定名稱的cookie(Cookie c = new Cookie("cookie的名稱","cookie的值");)
		Cookie cookie = MyCookieUtil.getCookieByName(cookies, "last");
		if(cookie==null){
			//說明是第一次訪問
			//列印一句歡迎
			response.getWriter().write("<h3>第一次訪問,歡迎!</h3>");
			//建立一個cookie,並將當前的時間儲存到cookie中去
			Cookie c = new Cookie("last",sDate);
			response.addCookie(c);
		}
		else{
			//不是第一次訪問了,獲取上一次訪問的時間
			String lastTime = cookie.getValue();
			response.getWriter().write("<h3>上次訪問的時間是:"+lastTime+"</h3>");
			cookie.setValue(sDate);
			response.addCookie(cookie);
		}
	}

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

}

商品的瀏覽記錄

JSP頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<style type="text/css">
	.img1{
	width:160px;
	height:140px;	
	}	
	.img2{
	width:80px;
	height:70px;
	}
</style>
<body>
	<img class="img1" src="/Product/img/1.jpg"><a href="/Product/product?id=1">手電筒</a>
	<img class="img1" src="/Product/img/2.jpg"><a href="/Product/product?id=2">電話</a>
	<img class="img1" src="/Product/img/3.jpg"><a href="/Product/product?id=3">電視</a>
	<br/>
	<img class="img1" src="/Product/img/4.jpg"><a href="/Product/product?id=4">冰箱</a>
	<img class="img1" src="/Product/img/5.jpg"><a href="/Product/product?id=5">手錶</a>
	<img class="img1" src="/Product/img/6.jpg"><a href="/Product/product?id=6">電腦</a>
	
	<h3>商品的瀏覽記錄</h3>
	<%
	//從cookie中獲取值
	Cookie[] cookies = request.getCookies();
	Cookie cookie = com.utils.MyCookieUtils.getCookieByName(cookies, "product");
	if(cookie!=null){
		String longId = cookie.getValue();
		//切割
		String[] ids = longId.split(",");
		String path = request.getContextPath();
		//遍歷
		for(String id:ids){
	%>
		<img class="img2" src="<%=path%>/img/<%= id %>.jpg">
	<%		
		}
	}
	%>
	
	
	
</body>
</html>

servlet響應

package com.servlet;

import java.io.IOException;

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;

import com.utils.MyCookieUtils;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().write("111");
		/*
		 * 1、獲取從客戶端傳過來的id值
		 * 2、判斷是否是第一次訪問(通過在cookie陣列中查詢指定名稱的cookie來判斷)
		 * 	如果是第一次訪問(獲取的cookie為null),建立一個指定名稱的cookie,將獲取的id值存入cookie,向客戶端回寫cookie
		 * 	如果不是第一次訪問,判斷獲取的id值是否已經存在於cookie中,如果是,則不操作,否則將這個id值存入cookie中
		 */
		//獲取id值
		String id = request.getParameter("id");
		//獲取cookie陣列
		Cookie[] cookies = request.getCookies();
		//查詢指定名稱的cookie
		Cookie cookie = MyCookieUtils.getCookieByName(cookies, "product");
		//判斷cookie
		if(cookie==null){
			Cookie c = new Cookie("product",id);
			//設定cookie的有效時間
			//c.setMaxAge(60*60);
			//設定訪問路徑
			c.setPath("/Product");
			//回寫到客戶端
			response.addCookie(c);
		}else{
			//獲取cookie的值
			String longId = cookie.getValue();
			//把cookie的值切割為字串陣列
			String[] ids = longId.split(",");
			//判斷longId中是否包含當前id
			//longId中不包含當前id,將當前id加入到cookie的值中
			if(!checkId(ids,id)){
				cookie.setValue(id+","+longId);
				//cookie.setMaxAge(60*60);
				cookie.setPath("/Product");
				//回寫到客戶端
				response.addCookie(cookie);
			}
		}
		//重定向或者轉發到商品顯示頁面,用request.getContextPath()獲取虛擬路徑,預設和專案名相同
		response.sendRedirect(request.getContextPath()+"/cookie/productList.jsp");
	}

	//判斷longId中是否包含當前id
	public boolean checkId(String[] ids,String id){
		for(String s:ids){
			if(s.equals(id)){
				return true;
			}
		}
		return false;
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

效果:

清楚商品的瀏覽記錄servlet

package com.servlet;

import java.io.IOException;

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;

import com.utils.MyCookieUtils;

@WebServlet("/removeProduct")
public class RemoveProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取cookie
		Cookie[] cookies = request.getCookies();
		Cookie cookie = MyCookieUtils.getCookieByName(cookies, "product");
		if(cookie!=null){
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		response.sendRedirect(request.getContextPath()+"/cookie/productList.jsp");
	}

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

}