JavaWeb-Cookie與顯示商品瀏覽記錄案例

客戶端的會話技術:cookie
				
	A.Cookie API

		1.創建Cookie對象.
		    Cookie cookie=new Cookie(String name,String value);
					
		2.獲取cookie名稱
			cookie.getName();
						
		3.獲取cookie值
			cookie.getValue();
						
		4.設置cookie爲持久化cookie。
			setMaxAge	
						
		cookie默認是會話級別,它保存在瀏覽器的緩存中,當關閉瀏覽器後,緩存中的內容清空。
						
		如果cookie使用了setMaxAge進行設置,這時cookie就是持久化的cookie。當瀏覽器關閉,
        持久化的cookie還存在。當重新打開瀏覽器,在發送請求,會將持久化的cookie.
			帶到服務器端.前提:cookie沒有過期.
						
		如果要刪除cookie持久化文件,只需要設置setMaxAge(0) 如果值爲負數,那麼會在瀏覽器
        關閉後刪除cookie。
						
		5.用於設置當前的cookie在什麼樣的uri訪問時纔會被帶到服務器端.
			setPath
			練習時可以簡單寫在  setPath("/");
													
						
	B.關於將cookie帶回到瀏覽器端.
		response.addCookie(Cookie c);
					
	C.在服務器端得到cookie
		Cookie[] cs=request.getCookies();

商品瀏覽記錄實例

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>顯示商品</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<a href="/HelloWeb/cookie/history.jsp">查看瀏覽記錄</a>
	<hr>
	<a href="/HelloWeb/Goods?id=1">西遊記</a>
	<br>
	<a href="/HelloWeb/Goods?id=2">紅樓夢</a>
	<br>
	<a href="/HelloWeb/Goods?id=3">水滸傳</a>
	<br>
	<a href="/HelloWeb/Goods?id=4">三國演義</a>
	<br>
</body>
</html>
<%@page import="demo.utils.CookieUtils"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>顯示商品瀏覽記錄</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<%
		String[] books = { "西遊記", "紅樓夢", "水滸傳", "三國演義" };

		//得到history這個cookie
		Cookie history = CookieUtils.getCookieByName(request.getCookies(),
				"history");
		if (history != null) {
			//得到history的vlaue值
			String value = history.getValue();
			String[] ids = value.split("-");
			for (int i = 0; i < ids.length; i++) {
				int id = Integer.parseInt(ids[i]) - 1;
	%>
	<%=books[id]%><br>
	<%
		}
		} else {
			out.print("無瀏覽記錄");
		}
	%>
</body>
</html>
package demo.cookie;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

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 demo.utils.CookieUtils;

public class GoodsServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 得到請求的參數
		String id = request.getParameter("id");

		// 得到history名稱的cookie
		Cookie[] cs = request.getCookies();
		Cookie history = CookieUtils.getCookieByName(cs, "history");
		String ids = null;
		// 如果history爲null,說明第一次訪問
		if (history == null) {
			ids = id;
		} else {
			// 不是第一次
			// 得到cookie中的value
			ids = history.getValue();
			// 考慮重複
			if (!Arrays.asList(ids.split("-")).contains(id)) {
				ids += "-" + id;
			}

		}
		// 存儲到cookie中
		history = new Cookie("history", ids);
		// 持久化
		// history.setMaxAge(30);

		// 再返回到響應中
		response.addCookie(history);
	}

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

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章