Cookie thường được set trong header HTTP (JavaScript cũng có thể set trực tiếp trên browser). JSP set cookie có thể gửi header như sau:
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html
Header Set-Cookie chứa: cặp name/value, ngày GMT, path và domain. Name/value được URL encoded. Trường expires yêu cầu browser "quên" cookie sau thời điểm đó.
Nếu browser cho phép lưu cookie, nó giữ thông tin đến ngày hết hạn. Khi user truy cập trang khớp path/domain, browser gửi lại cookie cho server. Header browser có dạng:
GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 ... Host: zink.demon.co.uk:1126 Accept: image/gif, */* Cookie: name = xyz
Script JSP truy cập cookie qua request.getCookies() trả về mảng đối tượng Cookie.