write a program to create a session cookie and display content of cookies
Answers
Answer:
When a user visits web application first time, the servlet container crates new HttpSession object by calling request.getSession(). A unique Id is assigned to the session. The Servlet container also sets a Cookie in the header of the HTTP response with cookie name and the unique session ID as its value.
The cookie is stored in the user browser, the client (user’s browser) sends this cookie back to the server for all the subsequent requests until the cookie is valid. The Servlet container checks the request header for cookies and get the session information from the cookie and use the associated session from the server memory.
The session remains active for the time specified in tag in web.xml. If tag in not set in web.xml then the session remains active for 30 minutes. Cookie remains active as long as the user’s browser is running, as soon as the browser is closed, the cookie and associated session info is destroyed. So when the user opens the browser again and sends request to web server, the new session is being created.
Types of Cookies
We can classify the cookie based on their expiry time:
Session
Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as the web browser is closed this cookie gets destroyed.
2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive and gets destroyed based on the expiry time.
How to send Cookies to the Client
Here are steps for sending cookie to the client:
Create a Cookie object.
Set the maximum Age.
Place the Cookie in HTTP response header.
1) Create a Cookie object:
Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}