運行頁面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
Cookie的運行原理:
1.第一次向服務器發送請求時在服務器端創建一個Cookie對象
2.將Cookie對象發送給瀏覽器
3.以後瀏覽器再發請求就會寫到着該Cookie對象
4.服務器根據不同的Cookie對象來區分不同的用戶
-->
<a href="${pageContext.request.contextPath }/CreateCookie">創建Cookie對象</a><br>
<a href="${pageContext.request.contextPath }/GetCookies">獲取 Cookie對象</a><br>
<a href="${pageContext.request.contextPath }/PersistCookies">持久化 Cookie對象</a>
</body>
</html>
Cookie的創建(Servlet):
/**
* 負責創建Cookie的Servlet
*/
public class CreateCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.創建Cookie對象
//Cookie對象的名字不能使用中文,Cookie對象的只可以使用中文但需要指定字符集進行編碼,
//而獲取Cookie對象還需要指定字符集進行解碼
Cookie cookie = new Cookie("user","admin");
Cookie cookie2 = new Cookie("user2","pathCookie");
//設置Cookie對象的有效期,默認Cookie對象的有效路徑是項目的根目錄
cookie2.setPath(request.getContextPath()+"/pages");
//2.將Cookie對象發送給瀏覽器
response.addCookie(cookie);
response.addCookie(cookie2);
}
獲取Cookie對象(Servlet):
/**
* 獲取Cookie對象的Servlet
*/
public class GetCookies extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取Cookie對象
Cookie[] cookies = request.getCookies();
if(cookies != null) {
//遍歷每一個Cookie對象
for(Cookie cookie : cookies) {
//獲取cookie對象的名字
String name = cookie.getName();
//獲取cookie對象的值
String value = cookie.getValue();
System.out.println("Cookie對象的名字是:"+name);
System.out.println("Cookie對象的值是:"+value);
}
}
}
創建持久化的Cookie(Servlet):
/**
* 持久化Cookie的Servlet
*/
public class PersistCookies extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//創建Cookie對象
Cookie cookie = new Cookie("user3","man");
//持久換Cookie對象爲1分鐘
/*
* setMaxAge(int age)
*
* age > 0 : Cookie對象age秒後失敗
* age = 0 : Cookie對象立即失敗
* age < 0 : 默認,會話級別的Cookie對象
*/
cookie.setMaxAge(60);
//將Cookie對象發送給瀏覽器
response.addCookie(cookie);
}