หากต้องการอ่านคุกกี้ คุณต้องสร้างอาร์เรย์ของ javax.servlet.http.Cookie ออบเจ็กต์โดยเรียก getCookies( ) วิธีการของ HttpServletRequest . จากนั้นวนไปตามอาร์เรย์ และใช้ getName() และ getValue() วิธีการเข้าถึงคุกกี้แต่ละรายการและค่าที่เกี่ยวข้อง
ให้เราอ่านคุกกี้ที่กำหนดไว้ในตัวอย่างก่อนหน้านี้ -
ตัวอย่าง
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html> ตอนนี้ให้เราใส่โค้ดด้านบนใน main.jsp ไฟล์และพยายามเข้าถึง หากคุณตั้งค่า คุกกี้ชื่อแรก เป็น "John" และ คุกกี้ชื่อสุดท้าย เป็น "ผู้เล่น" จากนั้นเรียกใช้ http://localhost:8080/main.jsp จะแสดงผลดังต่อไปนี้ −
ผลลัพธ์
Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player