Thiết lập cookie với JSP gồm 3 bước:
Bước 1: Tạo đối tượng Cookie
Gọi constructor Cookie với tên và giá trị (cả hai là chuỗi).
Cookie cookie = new Cookie("key","value");
Lưu ý: Tên và giá trị không được chứa khoảng trắng hoặc các ký tự: [ ] ( ) = , " / ? @ : ;
Bước 2: Thiết lập thời gian sống tối đa
Dùng setMaxAge chỉ định thời gian hợp lệ (giây). Code sau set cookie 24 giờ:
cookie.setMaxAge(60*60*24);
Bước 3: Gửi cookie vào header phản hồi HTTP
Dùng response.addCookie thêm cookie vào header:
response.addCookie(cookie);
Ví dụ hoàn chỉnh
<%
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);
lastName.setMaxAge(60*60*24);
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>
Đặt code trong main.jsp, dùng với HTML sau (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" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Đặt cả hai file vào <Tomcat-installation-directory>/webapps/ROOT. Truy cập https://localhost:8080/hello.jsp, nhập tên và nhấn Submit. Màn hình hiển thị tên và set 2 cookie firstName, lastName. Các cookie sẽ gửi lại server khi click Submit lần sau.