Cookies in Servlets Tutorial

A cookie is a small piece of information that is saved to client machine and send to server with each request.A cookie can contain single value,object value,expiry time etc.

By cookie we can also maintain user state on server as with each request cookie will be sent to the server.By matching the cookie we can identify the user’s state.Cookie can be following two types.

  • Persistent
  • Non-persistent

Persistent cookie is valid for multiple session. It is not removed each time when user closes the browser. It is removed only if user logout or signout.

Non-persistent is valid for single session only. It is removed each time when user closes the browser.

How to create Cookie

Cookie can be created by following two constructors of Cookie class.

  • Cookie()
  • Cookie(String name, String value)

Methods of Cookie

  • public void setMaxAge(int expiry): It is used to set the maximum age of the cookie in seconds.
  • public String getName(): It returns the name of the cookie. The name cannot be changed after creation.
  • public String getValue():It returns the value of the cookie.
  • public void setName(String name): It changes the name of the cookie. 
  • public void setValue(String value): It changes the value of the cookie.

Associating Cookie with Response

javax.servlet.http.HttpServletResponse interface provides addCookie() method to add cookie with response and it will created in client browser.

Signature of addCookie() method

public void addCookie(Cookie ck)

Fetch Cookie with Request

javax.servlet.http.HttpServletRequest interface has method getCookies() to get all cookies add by server to the request.

Signature of getCookies() method

public Cookie[] getCookies(): It will return all the cookies associated with request which is earlier set by server.

Example to create Cookie

//creating cookie object  
   Cookie ck=new Cookie("username","Gaurav Srivastav");
//Now adding cookie to the response

Example to delete Cookie

//delete value of cookie  
 Cookie ck=new Cookie("user","");
//changing the maximum age to 0 seconds to expire cookie

Leave a Reply