Advertisement



< Prev
Next >



Session management by Cookies





A cookie is one of the most common ways to track a user on internet and maintain a user's session. Cookie is a text file using which you can store the information in user's browser and access it when you need it. This makes cookie one of the techniques to maintain a user's session and to differentiate a user from the others. You can even specify the duration for which this Cookie file is going exist before it gets deleted by the browser.

Java Servlet Technology allows us to perform user's session management using its Cookie class.




Constructor of Cookie class


Constructor Description
void Cookie(String name, String value) Constructs a Cookie with a name and a value.





How to add a cookie


We can add cookie in the client's system by calling the addCookie() method of HttpServletResponse interface by using the response object.

Method Description
void addCookie(String name, String value) Adds a cookie within the client's browser.





Some useful methods of Cookie class.


The methods in the table below are part of javax.servlet.http.Cookie class, hence these methods are available to the object of Cookie class.

Methods Description
void setDomain(String name) Sets the domain name which will be associated with the Cookie.
String getDomain() Returns the domain name associated with the Cookie.
void setMaxAge(int expiry) Sets the maximum time(in seconds) till the Cookie lasts.
int getMaxAge() Returns the maximum time(in seconds) till the Cookie lasts.
void setComment(String message) Sets a message/comment describing the Cookie.
String getComment() Returns the message describing the Cookie.
void setValue(String value) Sets the value of the Cookie that is already created.
String getValue() Returns the value of the Cookie.



Advertisement




Creating a webpage which calls the Servlet


We are creating a webpage which asks the user to enter the name and city and press the submit button, which when clicked calls the Servlet with the <url-pattern> SaveCookie, specified in the deployment descriptor file(web.xml), passing this Servlet the parameters named username and cityname, using default get method.

Form1.htm
<html>

<head>
<title> Cookies Demo </title>
</head>


<body>
<b>Please enter your details :</b>

<br/>
<br/>

<form action = "SaveCookie" >
Name : <input  type = "text" name = "username"/>
City : <input type = "text"   name = "cityname" />
<input  type = "submit" name = "submit"/>
</form>

</body>
</html>





Creating, setting the Cookie using Servlet


In this Servlet, we are going to -

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement