1. 程式人生 > >cookies前後端操作(前端二)

cookies前後端操作(前端二)

目錄

伺服器端操作Cookies

客戶端每次請求都會附帶cookies資訊

服務端向前臺寫入Cookies

服務端程式碼

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

	// Cookie 處理需要對中文進行編碼與解碼
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 定義一個cookie物件
		Cookie cookie = new Cookie("color", URLEncoder.encode("黃色", "UTF-8"));
		Cookie name = new Cookie("name", URLEncoder.encode("zhang三", "UTF-8"));
		// 設定過期時間為24小時,以秒為單位
		cookie.setMaxAge(60 * 60 * 24);
		name.setMaxAge(60 * 60 * 1);
		// 新增cookie
		response.addCookie(cookie);
		response.addCookie(name);
		request.getRequestDispatcher("/cookie.html").forward(request, response);
	}

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

}

頁面展示端

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
	content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>提交表單測試</title>
</head>
<body>
	<form action="ReadCookieServlet" method="get">
		<h2>提交表單測試</h2>
		<p>
			名稱:<input type="text" name="txtName" id="txtName1" />
		</p>
		<p>
			價格:<input type="text" name="txtPrice" id="txtPrice1" value="888"
				readonly="readonly" />
		</p>
		<p>
			數量:<input type="text" name="txtAmount" id="txtAmount1" value="999"
				disabled="disabled" />
		</p>
		<input type="hidden" id="key" value="123445"> <input
			type="submit" value="提交" />
	</form>
</body>
</html>

測試,已經寫入
在這裡插入圖片描述

客戶端向服務端請求,傳遞Cookies

前臺程式碼為上面頁面共用html

服務端程式碼

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

	// Cookie 處理需要對中文進行編碼與解碼
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		Map<String, String> returnMap = new HashMap<>();
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
			returnMap.put(name, value);
		}
		
		Map<String, String[]> parameterMap = request.getParameterMap();
		for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
			returnMap.put(entry.getKey(), entry.getValue()[0]);
		}
		
		// 設定響應內容型別
        response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(returnMap);
	}

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

}

測試,點選提交
在這裡插入圖片描述
取出瀏覽器的cookies資訊
在這裡插入圖片描述

客戶端端操作Cookies

操作cookies的庫
https://github.com/js-cookie/js-cookie

對應html程式碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>客戶端讀寫Cookie</title>
<!-- 第三方操作cookies -->
<script src="js/js.cookie.min.js" type="text/javascript"></script>
<script type="text/javascript">
	function writeCookie() {
		var key = document.getElementById("key").value;
		var value = document.getElementById("value").value;
		var expire = document.getElementById("expire").value;
		//在當前域下寫入cookie
		Cookies.set(key, value, { expires: 7 });
		alert("操作成功");
	}
	function readCookie() {
		//在當前域根據key讀取cookie
		var key = document.getElementById("key").value;
		var value = Cookies.get(key);
		alert("值:" + value);
	}
	function removeCookie() {
		//在當前域指定的cookie
		var key = document.getElementById("key").value;
		Cookies.remove(key, { path: '/' });
		alert("清除:" + key);
	}
</script>
</head>
<body>
	<button type="button" onclick="writeCookie();">寫</button>
	<button type="button" onclick="readCookie();">讀</button>
	<button type="button" onclick="removeCookie();">清除</button>

	<div>
		<p>
			key:<input type="text" id="key" />
		</p>
		<p>
			value:<input type="text" id="value" />
		</p>
		<p>
			expire:<input type="text" id="expire" />
		</p>
	</div>
</body>
</html>

測試寫

在這裡插入圖片描述

在這裡插入圖片描述

測試讀

在這裡插入圖片描述

測試刪除