javaweb之Cookie顯示商品的瀏覽記錄和Cookie的常見應用有哪些

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

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

//代表首頁的servlet
public class CookieDemo3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.顯示網站的所有商品
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("本網站有如下商品:<br/>");
		Map<String, Book> map = Db.getAll();
		// 遍歷存有數據信息的“數據庫”顯示到頁面中
		for (Map.Entry<String, Book> entry : map.entrySet()) {
			Book book = entry.getValue();
			// 點擊超鏈接後,在新的頁面打開target="_blank"
			out.print("<a href='/day07/servlet/CookieDemo4?id=" + book.getId()
					+ "' target='_blank'>" + book.getName() + "</a><br/>");
		}

		// 2.顯示用戶曾經看過的商品
		out.print("<br/>您曾經看過如下商品:</br>");
		// 拿到請求中所有的Cookie
		Cookie cookies[] = request.getCookies();
		// 遍歷Cookie,看看有沒有瀏覽商品的Cookie
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			// 如果有瀏覽商品的Cookie則拿到其中的商品,瀏覽過的商品是很多件的,商品是以,分割的
			if (cookies[i].getName().equals("bookHistory")) {
				// 分割字符串,拿到留有瀏覽過的商品的id
				// 不管,有沒有在正則表達式中定義,都以,分割
				String[] ids = cookies[i].getValue().split("\\,"); // 2,3,1
				// 遍歷所有商品id獲得商品
				for (String id : ids) {
					Book book = Db.getAll().get(id);
					out.print(book.getName() + "<br />");
				}
			}
		}
	}

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

}

// 模擬數據庫,從這個類中提取書的信息
class Db {
	// 實際開發中存儲數據的集合有檢索數據的需求,都用雙列的(map),如果沒有檢索數據需求,用單列的(list、set)
	// LinkedHashMap是有序存儲
	private static Map<String, Book> map = new LinkedHashMap<String, Book>();
	// 對書進行靜態初始化
	static {
		// key是商品的id,value是商品,商品中也是有商品的id的
		map.put("1", new Book("1", "javaweb開發", "老張", "一本好書!"));
		map.put("2", new Book("2", "jdbc開發", "老張", "一本好書!"));
		map.put("3", new Book("3", "spring開發", "老黎", "一本好書!"));
		map.put("4", new Book("4", "struts開發", "老畢", "一本好書!"));
		map.put("5", new Book("5", "android開發", "老黎", "一本好書!"));
	}

	public static Map<String, Book> getAll() {
		return map;
	}
}

// 模擬書類
class Book {
	private String id;
	private String name;
	private String author;
	private String description;

	public Book() {
		super();
	}

	public Book(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;

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

//顯示商品詳細信息的servlet
public class CookieDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.根據用戶帶過來的id,顯示相應商品的詳細信息
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 獲取瀏覽的書的id
		String id = request.getParameter("id");
		// 根據id拿到書的信息
		Book book = Db.getAll().get(id);
		out.print(book.getId() + "<br/>");
		out.print(book.getAuthor() + "<br/>");
		out.print(book.getName() + "<br/>");
		out.print(book.getDescription() + "<br/>");

		// 2.構建Cookie,回寫給瀏覽器
		String cookieValue = buildCookie(id, request);

		Cookie cookie = new Cookie("bookHistory", cookieValue);
		cookie.setMaxAge(1 * 3600 * 24 * 30);
		cookie.setPath("/day07");
		response.addCookie(cookie);
	}

	// 構建Cookie的方法
	private String buildCookie(String id, HttpServletRequest request) {
		// 1.用戶沒有帶Cookie過來 bookHistory=null id=1 return 1
		// 2.用戶帶Cookie過來 bookHistory=2,5,1 id=1 bookHistory中包含id
		// 要把2,5,1中的1刪掉加在最前面 return1,2,5
		// 3.用戶帶Cookie過來 bookHistory=2,5,4 id=1 假設列表最大顯示3個Cookie return1,2,5
		// 4.用戶帶Cookie過來 bookHistory=2,5 id=1 並且列表沒有超出範圍 return 1,2,5

		// 先把要Cookie的值創建出來
		String bookHistory = null;
		// 得到Cookie,看看有沒有bookHistory這個Cookie,有的話,把它的值賦給bookHistory(要返回的String類型的)
		Cookie[] cookies = request.getCookies();
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			if (cookies[i].getName().equals("bookHistory")) {
				bookHistory = cookies[i].getValue();
			}
		}

		// 第一種可能,那麼返回的就是瀏覽的這個商品的id
		if (bookHistory == null) {
			return id;
		}
		// 第二種可能,要判斷有沒有包含,要先轉成List,調用List的方法判斷String.content判斷出來的數據是有錯誤的,判斷1的話21也包含
		// 由於增刪改查操作較多,所以用鏈表
		LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory
				.split("\\,")));
		/*
		 * if(list.contains(id)) { list.remove(id); list.addFirst(id); } else {
		 * //第三種和第四種可能 //第三種可能 if(list.size()>=3) { list.removeLast();
		 * list.addFirst(id); } else { //第四種可能 list.addFirst(id); } }
		 */
		// 上面的代碼優化,不管怎麼樣都要list.addFirst(id);
		if (list.contains(id)) {
			list.remove(id);
		} else {
			if (list.size() >= 3) {
				list.removeLast();
			}
		}
		list.addFirst(id);

		// 將list中的數據構建字符串返回
		StringBuffer sb = new StringBuffer();
		for (String bid : list) {
			sb.append(bid + ",");
		}
		return sb.deleteCharAt(sb.length() - 1).toString();
	}

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

}

Cookie常見應用:顯示上次訪問網站的時間、顯示瀏覽過的商品、做購物(購物車)、自動登錄(Cookie把用戶的用戶名和密碼回寫給瀏覽器,但是寫這個程序的時候用戶名是直接回寫的,密碼是通過加密後回寫的)


發佈了58 篇原創文章 · 獲贊 26 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章