Cookies ทำงานผ่าน HTTP headers ระหว่างเซิร์ฟเวอร์และเบราว์เซอร์
1. เซิร์ฟเวอร์ส่ง Cookie (Response Header)
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=example.com Connection: close Content-Type: text/html
องค์ประกอบของ Set-Cookie:
- name=value - คู่คีย์-ค่า (URL encoded)
- expires - วันหมดอายุ (GMT) หลังวันนี้ browser จะลบ cookie
- path - path ที่ cookie ทำงาน (default = path ปัจจุบัน)
- domain - โดเมนที่ cookie ทำงาน
- HttpOnly - ห้าม JavaScript เข้าถึง (security)
- Secure - ส่งเฉพาะ HTTPS
2. เบราว์เซอร์ส่ง Cookie กลับ (Request Header)
เมื่อ user request URL ที่ match path และ domain:
GET / HTTP/1.0 Connection: Keep-Alive Cookie: name=xyz Host: example.com
3. JSP เข้าถึง Cookie
ผ่าน implicit object request:
Cookie[] cookies = request.getCookies();
Flow สรุป
- JSP เรียก
response.addCookie(cookie) - Container สร้าง
Set-Cookieheader - Browser รับ เก็บใน cookie store
- Request ถัดไป Browser ส่ง
Cookieheader - Container parse ใส่
request.getCookies()
JavaScript ก็สามารถตั้ง/อ่าน cookies ได้ผ่าน document.cookie แต่ JSP ใช้ server-side headers