MY mENU


Saturday 26 May 2012

Working with Cookie in JSP


Cookie is a small piece of information which is stored in user's computer. Webserver uses cookie to identify the user in the next time visit.

Each time user visits a website which cookie is enable, the web server adds extra data into the HTTP header and responds to the web browser. in the next time when user visits the same site again, the web browser also sends cookie in the HTTP request header to the web server.
User can also disables cookie in the web browser which supports disable cookie function such as Mozilla Firefox, IE...
Cookie is stored in the user's computer as a string of name/value. In addition, cookie has attributes such as domain, path, timeout...
JSP provides API to allows you to work with cookie effectively through object of the class javax.server.http.Cookie. Let's take a look at an example how to set cookie in JSP and respond it back to the client.

Sending cookie from the web server

In the code, first you create a new cookie with the name and value. If you se the methods such as setDomain()  and setPath() to restrict the cookie to the current URL you have to read the cookie exactly from that URL. Cookie has its own lifetime called expiration time. If you don't set the timeout for the cookie, it will be removed when user closes the web browser. The method setMaxage() is used to set the expiration time for the cookie. Finally you add cookie to the response header and store it in the user's computer by using methodaddCookie() of response object.

Reading cookie

To read cookie from a HTTP request, you first call the method getCookies() of the requestobject. This method returns you a list of available cookies in the request header, then you can walk through all of them. Here is the code to read cookie information:
Removing existing cookie
If you want to remove an existing cookie you've sent to the web browser, you can use the method setMaxAge() of that cookie object to set its timeout to zero. This is the sample code to remove all the cookies.

No comments:

Post a Comment