การตั้งค่าคุกกี้ด้วย JSP มีสามขั้นตอน -
ขั้นตอนที่ 1:การสร้างวัตถุคุกกี้
คุณเรียกใช้ตัวสร้างคุกกี้ด้วยชื่อคุกกี้และค่าคุกกี้ ซึ่งทั้งคู่เป็นสตริง
Cookie cookie = new Cookie("key","value"); โปรดจำไว้ว่า ชื่อหรือค่าไม่ควรมีช่องว่างหรืออักขระใด ๆ ต่อไปนี้ -
[ ] ( ) = , " / ? @ : ;
ขั้นตอนที่ 2:การตั้งค่าอายุสูงสุด
คุณใช้ setMaxAge เพื่อระบุระยะเวลา (เป็นวินาที) ที่คุกกี้ควรใช้งานได้ รหัสต่อไปนี้จะตั้งค่าคุกกี้เป็นเวลา 24 ชั่วโมง
cookie.setMaxAge(60*60*24);
ขั้นตอนที่ 3:การส่งคุกกี้ไปยังส่วนหัวการตอบสนอง HTTP
คุณใช้ response.addCookie เพื่อเพิ่มคุกกี้ในส่วนหัวตอบกลับ HTTP ดังนี้
response.addCookie(cookie);
ตัวอย่าง
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html> ให้เราใส่โค้ดด้านบนใน main.jsp ไฟล์และนำไปใช้ในหน้า HTML ต่อไปนี้ -
<html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
เก็บเนื้อหา HTML ข้างต้นไว้ในไฟล์ hello.jsp แล้วใส่ hello.jsp และ main.jsp ใน
ผลลัพธ์

ลองใส่ชื่อและนามสกุลแล้วคลิกปุ่มส่ง ซึ่งจะแสดงชื่อและนามสกุลบนหน้าจอของคุณและจะตั้งค่าคุกกี้ ชื่อสองคุกกี้ และ นามสกุล . คุกกี้เหล่านี้จะถูกส่งกลับไปยังเซิร์ฟเวอร์เมื่อคุณคลิกปุ่มส่งครั้งต่อไป