Professional Documents
Culture Documents
JSP Session Tracking: Cookies
JSP Session Tracking: Cookies
Cookies
small piece of information which is stored
in user’s computer.
The web server uses a cookie to identify
the user in the next time visit.
A cookie has attributes such as domain,
path, and timeout.
JSP provides API to allows you to work
with cookie effectively through the object of
the class javax.servlet.http.Cookie.
If cookie is associated with the client
request, server will associate it with
corresponding user session otherwise it will
create a new unique cookie and send it back
with response.
Cookie objects are can be created using a
name value pair.
For example, we can create a cookie with
the name sessionId and with a unique value for
each client.
Later this can be added it in a response so
that it will be sent back to the client.
Syntax of creating Cookie in a JSP is:
Cookie cookie = new Cookie(“sessionID”, “some
unique value”);
response.addCookie(cookie);
Creating cookies
1) Creating a Cookie object-
1. <%@page import="javax.servlet.http.Cookie"%>
2. <html>
3. <head>
4. <title>JSP Create Cookie</title>
5. </head>
6. <body>
7. <%
8. Cookie cookie = new Cookie("ClientID","username");
9. cookie.setMaxAge(3600);
10. response.addCookie(cookie);
11. %>
12. </body>
13. </html>
Reading Cookies
To read a cookie from an HTTP request,
first call the method getCookies() of
the request object.
This method returns a list of available
cookies in the request header, then walk
through all of them.
1. <%@page import="javax.servlet.http.Cookie"%>
2. <html>
3. <head>
4. <title>JSP Read Cookie</title>
5. </head>
6. <body>
7. <%
8. Cookie[] list = request.getCookies();
9. if (list != null){
10. for (int i = 0; i < list.length;i++){
11. out.println(list[i].getName() + ":" +
list[i].getPath());
12. }
13. }
14. %>
15. </body>
16. </html>