Cookie in Servlet

A Cookie is a small piece of data sent by a server to the client’s browser, which is then stored locally. Cookie in Servlet is often used to maintain user sessions, personalize content, or store user preferences.

First, let’s understand how cookie works:

how to use cookie in servlet
Cookie in Servlet 6

Set Cookie in Servlet

In this section, we focus on how to set cookies in a servlet. Cookies are small pieces of data stored on the client’s machine, and they are commonly used for session management or personalization. The example servlet, SetCookieExampleServlet, illustrates the process of creating a new cookie and adding it to the response.

import java.io.IOException;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/set-cookie")
public class SetCookieServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // Create a new cookie and add it to the response
        Cookie newCookie = new Cookie("username", "CoderSathi");
        newCookie.setMaxAge(24 * 60 * 60); // Set the cookie's maximum age to 1 day (in seconds)
        response.addCookie(newCookie);

        // Set the content type of the response
        response.setContentType("text/html");

        // Create a PrintWriter to send the response
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h2>Setting Cookies in Servlet</h2>");
        response.getWriter().println("<p>Cookie 'username' set with value 'CoderSathi'.</p>");
        response.getWriter().println("</body></html>");
    }
}

In the above code, we did the following:

  • We create a new instance of the Cookie class, naming it “username” and assigning it the value “CoderSathi”
  • We set the maximum age of the cookie to 1 day using newCookie.setMaxAge(24 * 60 * 60), making it expire after 24 hours.
  • The cookie is added to the response using response.addCookie(newCookie).
  • The HTML response informs that the cookie “username” has been set with the value “CoderSathi”

Get Cookie in Servlet

This section outlines the process of retrieving and using cookies in a servlet. The example servlet, GetCookieServlet, checks if a specific cookie named “username” exists. If found, it retrieves its value and uses it in the response.

import java.io.IOException;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/get-cookie")
public class GetCookieServlet extends HttpServlet {


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// Check if the client has a specific cookie
		Cookie[] cookies = request.getCookies();
		String username = null;

		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("username".equals(cookie.getName())) {
					username = cookie.getValue();
					break;
				}
			}
		}

		// Set the content type of the response
		response.setContentType("text/html");

		// Create a PrintWriter to send the response
		response.getWriter().println("<html><body>");
		response.getWriter().println("<h2>Getting Cookies in Servlet</h2>");

		// Display the username if available in the cookie
		if (username != null) {
			response.getWriter().println("<p>Welcome back, " + username + "!</p>");
		} else {
			response.getWriter().println("<p>No username cookie found.</p>");
		}

		response.getWriter().println("</body></html>");
	}
}

Let’s understand the aboce code:

  • We obtain an array of cookies from the client’s request using Cookie[] cookies = request.getCookies().
  • We iterate through the array to find the cookie named “username” and retrieve its value.
  • The HTML response displays a welcome message if the “username” cookie exists, or notifies that no such cookie is found if it doesn’t.

Test our application

When we try to get our cookie we will get the following output:

Cookie in Servlet Get Cookie First
Cookie in Servlet 7

This is because, we haven’t set any cookie yet.

Now, let’s run another URL that set’s the cookie.

Cookie in Servlet Set Cookie
Cookie in Servlet 8

It shows a message saying, the cookie is added.

Now again, try to access get cookie url and we may see that the message is displayed from the cookie:

Cookie in Servlet Get Cookie Again
Cookie in Servlet 9

If you compare with first output the message was: No username cookie found.

Let’s verify in our browser with the following steps:

  1. Go to your browser
  2. Right click and select on Inspect or Inspect Element
  3. Select Application tab
  4. On the left, got to Storage and select Cookies. You may see the followin output:
Cookie in Servlet Cookie Verified
Cookie in Servlet 10

Frequently Asked Questions (FAQs)

How long do Cookies persist in Java Servlets?

Cookies can have different lifetimes. Some cookies are temporary and exist only for the duration of the user’s session, while others can persist for a specified period or until the user manually deletes them.

What information can be stored in a Cookie?

Cookies can store simple string values, such as user preferences or session identifiers. It’s important not to store sensitive information in cookies due to security concerns.

How do I delete a Cookie in Java Servlets?

To delete a cookie, you need to create a new cookie with the same name as the one you want to delete and set its maximum age to 0. Then, add this cookie to the response using the addCookie method.

Are there security considerations when using Cookies in Java Servlets?

Yes, there are security considerations. Always avoid storing sensitive information in cookies, and consider using secure and HttpOnly flags to enhance cookie security. Additionally, be cautious of potential security vulnerabilities, such as Cross-Site Scripting (XSS) attacks.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments