Working with Cookie in JSP

In this tutorial, you will have a basic understanding about the cookie and how to work with the cookie by using JSP API.

A cookie is a small piece of information which is stored in user’s computer. The web server uses a cookie to identify the user in the next time visit.

Each time user visits a website which cookie is enabled, the web server adds extra data into the HTTP header and responds to the web browser. in the next time when a user visits the same site again, the web browser also sends a cookie in the HTTP request header to the web server.

The user can also disable cookie in the web browser which supports disable cookie function such as Mozilla Firefox, IE…

A cookie is stored on the user’s computer as a string of name/value. In addition, a cookie has attributes such as domain, path, and timeout.

JSP provides API to allows you to work with cookie effectively through the object of the class javax.servlet.http.Cookie.

Let’s take a look at an example how to set a 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 use 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 the user closes the web browser. The method setMaxage() is used to set the expiration time for the cookie. Finally, you add a cookie to the response header and store it in the user’s computer by using methodaddCookie() of the response object.

Reading cookie

To read a cookie from an HTTP request, you first call the method getCookies() of the request object. 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.

  • Was this tutorial helpful ?
  • YesNo