Cookies in Servlets
Introduction
- Cookies are small piece of data on the client computer that send response from the web server to client.
- They are used to store the client state.
- The information which is stored on the client machine is called cookie.
- A Servlet container sends small information to the web browser. This data is saved by the browser and later back to the server.
- The servlet sends cookies to the browser using HttpServletResponse.addCookie(javax.servlet.http.Cookie) method.
Types of Cookies
Two types of cookies presents in Servlets:
1. Non-persistent/session cookie
2. Persistent cookie
1. Non-persistent/session cookie
Non-persistent cookies do not have an expiry time. They are valid for a single session only. The persistent cookies are live till the browser is open. They disappear when user closes the browser.
2. Persistent cookie
Persistent cookies have expiry time parameter. They are valid for multiple sessions. They do not disappear when user closes the browser. They are stored in primary memory of the computer. They disappear when user logs out or signs out.
Cookie Class Constructors
Constructor | Description |
---|
Cookie( ) | Constructs the cookie with default property. |
Cookie(String name, String value) | Constructs a cookie with specified name and value. |
Cookie Class Methods
Following are some important methods of Cookie class:
Methods | Description |
---|
public String getName( ) | Returns the name of the cookies. |
public String getPath( ) | Returns the path of the server to which the browser returns the cookie. |
public String getValue( ) | Returns the value of the cookie. |
public int getMaxAge( ) | Returns the maximum age limit to the cookie, specified in seconds. |
public void setMaxAge(int expiry) | Sets the maximum age of the cookies in seconds. |
public void setValue(String newValue) | Allocates a new value to a cookie after the cookie is created. |
Create a Cookie Object
The constructor of Cookie class creates the cookie object with corresponding cookie name and value.
Example
Cookie cookie = new Cookie("username","Surendra");
Response.addCookie(cookie);
Reading Cookie Sent from the Browser
The
getCookies( ) method is used for getting the cookie.
Example
Cookie[ ] cookies = request.getCookies( );
String username = null;
for (Cookie cookie : cookies)
{
if("user".equals(cookie.getName( )))
{
username = cookie.getValue();
}
}
Deleting the Cookies
We can remove the cookies from the browser by setting the cookie expiry time to
0 or -1.
Example
Cookie cookie = new Cookie("user", "");
cookie.setMaxAge(0);
response.addCookie(cookie);