Sunday, 24 April 2016

How do I send and receive cookies from a Servlet ?


HTTP is a stateless protocol, which makes tracking user actions difficult.

For session tracking, cookies can be used which are a small pieces of data sent by a web browser every time it requests a page from a particular site.
Servlets can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.

// Create a new cookie

Cookie cookie = new Cookie ("counter", "1");


ADDING A COOKIE
You can call HttpServletResponse.addCookie() method multiple times, but remember that number of cookies and data size in a request is specific to browser.

public void doGet(HttpServletRequest request, 
     HttpServletResponse response) throws IOException {

   response.addCookie( new Cookie("cookie_name", "cookie_value") );
}


READING COOKIES
You can use method HttpServletRequest.getCookies() inside servlet's doGet, doPost, etc. methods.
If no cookies are available, it may be null, so be sure to check before accessing any array element.

// Check for cookies
Cookie[] cookie_jar = request.getCookies();

// Check to see if any cookies exists
if (cookie_jar != null)  {
  for (int i =0; i< cookies.length; i++)  {
     Cookie aCookie = cookie_jar[ i ];
     out.println ("Name : " + aCookie.getName());
     out.println ("Value: " + aCookie.getValue());
    }

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.