Java Servlet Cookies Example

Welcome to Java Servlet Cookies example. Cookies are used a lot in web client-server communication, it’s not something specific to java.

Some of the common usage of cookies are:

  1. Session authentication using Cookies, we learned in Servlet Session Tutorial that HttpSession uses “JSESSIONID” cookie to keep track of the user session.
  2. Personalized response to the client based on their preference, for example we can set background color as cookie in client browser and then use it to customize response background color, image etc.

Cookies in Java Servlet

Cookies are text data sent by server to the client and it gets saved at the client local machine. When client send request to server, it passes the cookies stored by the server in request header like below:

Client can send multiple cookies to server and we can disable cookies to get stored at client side from browser preferences. Apart from the key-value pairs, server sends some other data to client in response header and it looks something like below.

Note that server sends some additional information for cookie, such as comment, domain, maximum time before cookie expires and Path where browser should send the cookie back in request. But when client sends cookie to browser, it only sends the name and value of the cookie.

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.

Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

Cookie class has a single constructor that takes name and value because they are mandatory parameters for a cookie, all other parameters are optional.

Some important methods of Cookie class are:

  1. getComment() – Returns the comment describing the purpose of this cookie, used at client side. Note that server doesn’t receive this information when client sends cookie in request header. We can use setComment() method to set cookie description at server side.
  2. getDomain() – returns the domain name for the cookie. We can use setDomain() method to set the domain name for cookie, if domain name is set then the cookie will be sent only to that particular domain requests.
  3. getMaxAge() – returns the maximum age in seconds. We can use setMaxAge() to set the expiration time of cookie.
  4. getName() – returns the name of the cookie, can be used at both browser and server side. There is no setter for name, we can set name once through constructor only.
  5. getPath() – Returns the path on the server to which the browser returns this cookie. We will see it’s example where the cookie will be sent to specific resource only. We can use setPath() to instruct browser to send cookie to a particular resource only.
  6. getSecure() – Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. We can use setSecure() method to instruct browser to send cookie only over secured protocol.
  7. getValue() – returns the value of the cookie as String. There is also setValue() method to change the value of cookie.
  8. getVersion() – Returns the version of the protocol this cookie complies with. There is also a setter method for version.
  9. isHttpOnly() – Checks whether this Cookie has been marked as HttpOnly. There is also a setter method that we can use to instruct client to use it for HTTP only.

Java Servlet Cookie Example

We will create two simple servlets to print cookies from client, in one of the servlet we will set a cookie for every domain and a cookie with Path settings so that other servlet won’t receive this from client.

Our final project structure for cookies in java servlet will look like below image.

Servlet-Cookie-Project This servlet will set some cookies and send it to browser. It will also print cookie information and send it as HTML response. A simple servlet that will demonstrate that the cookie set in SetCookie with specific Path will not be send by browser to this servlet.

When you will run the program, you will notice few things:

  • Cookie “Counter” is sent over to the SetCookie only, GetCookie will never receive this cookie.
  • Except name and value all other variables are printing default values. MaxAge default value is -1 and version default value is 0.
  • GetCookie is setting max age of “Test” cookie to 0, so that it will be expired and deleted by client browser.

That’s all for cookies in java and it’s usage in Servlet API, you might want to check out other servlet tutorials too.

  1. Java Web Application
  2. Servlet JSP Tutorial
  3. Session Management in Java
  4. Java Servlet Filter
  5. Servlet Listener

Check out next articles in series about Servlet Exception Handling and Servlet File Upload Download Example.

By admin

Leave a Reply