Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีตั้งค่า Cookies ใน JSP

การตั้งค่า cookie ใน JSP มี 3 ขั้นตอน:

ขั้นตอนที่ 1: สร้าง Cookie object

Cookie cookie = new Cookie("key", "value");

ชื่อและค่าไม่ควรมี whitespace หรือตัวอักขระพิเศษ: [ ] ( ) = , " / ? @ : ;

ขั้นตอนที่ 2: ตั้งอายุ cookie (Max Age)

cookie.setMaxAge(60 * 60 * 24);  // 24 ชั่วโมง (วินาที)
  • ค่าบวก = persistent cookie (วินาที)
  • 0 = ลบ cookie
  • -1 = session cookie (ค่าเริ่มต้น หายเมื่อปิดเบราว์เซอร์)

ขั้นตอนที่ 3: ส่ง cookie ไปใน response header

response.addCookie(cookie);

ตัวอย่างสมบูรณ์: ตั้งค่า first_name และ last_name

<%
    Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
    Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
    
    firstName.setMaxAge(60 * 60 * 24);  // 24 ชม.
    lastName.setMaxAge(60 * 60 * 24);
    
    response.addCookie(firstName);
    response.addCookie(lastName);
%>
<html>
<head><title>ตั้งค่า Cookies</title></head>
<body>
    <center><h1>ตั้งค่า Cookies</h1></center>
    <ul>
        <li><b>First Name:</b> <%= request.getParameter("first_name") %></li>
        <li><b>Last Name:</b> <%= request.getParameter("last_name") %></li>
    </ul>
</body>
</html>

ไฟล์ HTML ทดสอบ (hello.jsp)

<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" /><br/>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

วิธีทดสอบ

  1. วาง hello.jsp และ main.jsp ใน <Tomcat>/webapps/ROOT/
  2. เปิด https://localhost:8080/hello.jsp
  3. กรอกชื่อ กด Submit → main.jsp แสดงผลและตั้ง cookie
  4. Refresh หรือ Submit อีกครั้ง → cookie จะส่งมาพร้อม request

ข้อแนะนำเพิ่มเติม

  • ตั้งค่า cookie.setHttpOnly(true) เพื่อป้องกัน XSS
  • ตั้งค่า cookie.setSecure(true) สำหรับ HTTPS only
  • ตั้งค่า cookie.setPath("/") ให้ทำงานทั้งเว็บไซต์