CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Cookie in Servlet

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

Cookie in Servlet

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 ยท 4 min read ยท 0 Comments
Share: in X

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

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:

Get Cookie First

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

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

Set Cookie

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:

Get Cookie Again

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 Verified

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.

Related Posts:

  • Send Email Using Java
  • How To Read Servlet Parameters in Java: A Step-by-Step Guide
  • How to Run DeepSeek AI Locally Using Ollama: A…
  • Servlet Redirections
  • A Simple Servlet Program in Java
  • Pagination and Sorting in Spring Boot
Tags:javaserver-side-prograingservlet
Was this article helpful?
โ† Previous ArticleHow To Read Servlet Parameters in Java: A Step-by-Step Guide
Next Article โ†’How to disable SSL require in MySQL Workbench

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
ยฉ 2026 CoderSathi. All rights reserved. Privacy Policy ยท Sitemap