Cookies in JSP With Example

โšก Smart Summary

JSP Cookies are small text files stored on the client browser that help JSP applications track sessions, remember user preferences, and personalize responses across multiple HTTP requests using the javax.servlet.http.Cookie API and standard response headers.

  • ๐Ÿช Definition: JSP Cookies are key value text files stored on the client device and read through the request object on each subsequent HTTP call.
  • ๐Ÿ” Security flags: Setting Secure, HttpOnly, and the modern SameSite attribute protects JSP Cookies from interception, script access, and cross site request forgery.
  • โฑ๏ธ Lifetime control: The setMaxAge method decides whether a JSP Cookie is persistent on disk or removed automatically when the browser session ends.
  • โœ… Standard API: The javax.servlet.http.Cookie class with response.addCookie and request.getCookies covers creation, transmission, retrieval, and deletion in Servlet 4.x and 5.x.
  • ๐Ÿงช Worked example: A two page username and email demo shows how JSP Cookies are created, sent, persisted for ten hours, and read back on the next request.

Cookies in JSP With Example

What Are JSP Cookies?

JSP Cookies are small text files that a JSP based web server asks the client browser to store on the user device. Because HTTP is a stateless protocol, JSP Cookies provide a simple, standards based way to remember information between requests, such as login state, language choice, theme, or shopping cart identifiers.

  • JSP Cookies are plain text files stored on the client machine by the browser.
  • They are used to track information for session management, personalization, and analytics.
  • JSP supports HTTP cookies through the underlying Servlet technology and the javax.servlet.http.Cookie class.
  • JSP Cookies are transmitted inside HTTP request and response headers on every matching request.
  • When the browser is configured to accept cookies, it stores them on disk until the expiry date set by setMaxAge.

Why Use JSP Cookies?

JSP developers rely on cookies because HTTP requests are independent of each other. Without JSP Cookies, the server would not know that two requests belong to the same visitor. Cookies in JSP solve this problem with minimal server side state.

  • Session tracking: A JSESSIONID cookie connects multiple page views to one logical session.
  • Personalization: JSP Cookies can store language, theme, or layout preferences.
  • Authentication helpers: Remember me tokens and login state often live in cookies with the HttpOnly and Secure flags enabled.
  • Analytics: Cookies in JSP record return visitors, referrers, and conversion paths.

Types of JSP Cookies

  1. Persistent Cookie: A persistent JSP Cookie remains stored on the device for the time set with setMaxAge. It helps the application remember preferences and login details across browser restarts.
  2. Non persistent Cookie: A non persistent JSP Cookie, also called a session cookie, lives only in browser memory and is removed when the user closes the browser. It is mostly used for short lived session tracking.

JSP Cookies Methods

The javax.servlet.http.Cookie class exposes the following methods used most often when working with JSP Cookies.

  • public void setDomain(String domain)

    This JSP set cookie method sets the domain to which the JSP Cookie applies.

  • public String getDomain()

    This JSP get cookie method returns the domain to which the JSP Cookie applies.

  • public void setMaxAge(int expiry)

    It sets the maximum time in seconds before the JSP Cookie expires. A value of zero deletes the cookie and a negative value makes it a session cookie.

  • public int getMaxAge()

    It returns the maximum age of the JSP Cookie in seconds.

  • public String getName()

    It returns the name of the JSP Cookie.

  • public void setValue(String value)

    Sets the value associated with the JSP Cookie.

  • public String getValue()

    Returns the value associated with the JSP Cookie.

  • public void setPath(String path)

    This set cookie in JSP method sets the URL path to which the cookie applies.

  • public String getPath()

    It returns the URL path to which the JSP Cookie applies.

  • public void setSecure(boolean flag)

    It marks the JSP Cookie so that it is sent only over encrypted HTTPS connections.

  • public void setComment(String cmt)

    It describes the purpose of the JSP Cookie.

  • public String getComment()

    It returns the comment describing the JSP Cookie.

How to Handle JSP Cookies

Working with JSP Cookies involves three repeatable steps. The same pattern is used for login state, theme switches, and shopping carts.

  1. Create the JSP Cookie object using the Cookie constructor.
  2. Configure the cookie attributes, especially the maximum age, path, and security flags.
  3. Send the cookie to the browser through HTTP response headers using response.addCookie.

How to Create a JSP Cookie

A new JSP Cookie is created by instantiating javax.servlet.http.Cookie with a name and a value. The cookie is then attached to the response object so that the browser stores it.

How to Read JSP Cookies

On every subsequent request, the browser sends matching JSP Cookies back to the server. The page reads them by calling request.getCookies, which returns an array of Cookie objects. The application then iterates over the array, looks up each cookie by name, and uses its value.

How to Delete a JSP Cookie

To delete a JSP Cookie, the server creates a new cookie with the same name, sets its value to an empty string, calls setMaxAge with zero, and adds it to the response. The browser then removes the stored cookie on the next response.

Example of Cookies in JSP

In this JSP Cookies example, the application creates two cookies for username and email, keeps them alive for ten hours, and then reads the values back on a second page called action_cookie_main.jsp.

Action_cookie.jsp

<%-- Action_cookie.jsp: input form for JSP Cookies demo --%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Cookie</title>
</head>
<body>
<form action="action_cookie_main.jsp" method="GET">
Username: <input type="text" name="username">
<br />
Email: <input type="text" name="email" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Action_cookie_main.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%

   Cookie username = new Cookie("username",
 			  request.getParameter("username"));
   Cookie email = new Cookie("email",
			  request.getParameter("email"));


   username.setMaxAge(60*60*10);
   email.setMaxAge(60*60*10);

   // Add both the JSP Cookies in the response header.
   response.addCookie( username );
   response.addCookie( email );
%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Cookie JSP</title>
</head>
<body>

<b>Username:</b>
   <%= request.getParameter("username")%>
<b>Email:</b>
   <%= request.getParameter("email")%>

</body>
</html>

Explanation of the Code

Action_cookie.jsp

Code Line 10 to 15: The page declares a form that is submitted to action_cookie_main.jsp. Two input fields, username and email, collect data from the user along with a submit button.

Action_cookie_main.jsp

Code Line 6 to 9: Two Cookie objects, username and email, are created using request.getParameter to read the values submitted by the form.

Code Line 12 to 13: The setMaxAge method is called with 60 multiplied by 60 multiplied by 10, which sets the lifetime of each JSP Cookie to ten hours.

Code Line 16 to 17: The two cookies are attached to the response with response.addCookie. The browser then sends them back on subsequent requests, and the server reads them using request.getCookies or request.getParameter for the current request.

Output

When you execute the above code you get the following output.

JSP Cookies Methods

JSP Cookies Methods

When action_cookie.jsp is executed, the browser shows the two fields, username and email. After the user fills them in and clicks Submit, action_cookie_main.jsp creates the matching JSP Cookies on the server, stores them on the client, and displays the values, confirming that the cookies were created successfully.

Best Practices for JSP Cookies

Modern web applications should treat JSP Cookies as security sensitive data. The following practices align with current Servlet 4.x and Servlet 5.x deployments.

  • Use HttpOnly: Mark authentication cookies as HttpOnly so that client side scripts cannot read them.
  • Use Secure: Send cookies only over HTTPS by calling setSecure(true).
  • Use SameSite: Configure the SameSite attribute (Lax or Strict) through the container or response headers to mitigate cross site request forgery.
  • Keep values small: Store an identifier in the cookie and keep the data in server side storage.
  • Set explicit expiry: Use setMaxAge for predictable behavior across browsers.

FAQs

JSP Cookies are small text files that store data on the client browser. JSP pages use them for session tracking, remembering user preferences, supporting login state, and powering analytics across multiple HTTP requests to the same web application.

Mark cookies as HttpOnly so scripts cannot read them, call setSecure(true) so they travel only over HTTPS, and configure the SameSite attribute as Lax or Strict to reduce cross site request forgery risk in modern browsers.

Create a new Cookie with the same name and path, set its value to an empty string, call setMaxAge(0), and add it to the response with response.addCookie. The browser then removes the matching stored cookie immediately.

A persistent JSP Cookie has a positive maximum age and is stored on disk until that time expires. A session cookie has a negative maximum age, lives only in browser memory, and is removed when the browser window is closed.

AI driven analytics can score cookie traffic in real time, flag stolen session identifiers, detect unusual geolocation jumps, and trigger step up authentication. Machine learning models also help tune SameSite, HttpOnly, and Secure policies based on observed attack patterns.

Yes. AI assistants can scan legacy JSP and Servlet code, rewrite javax.servlet.http.Cookie calls for jakarta.servlet.http.Cookie in Servlet 5.x, add SameSite and HttpOnly flags, and suggest safer storage of session identifiers without breaking existing application logic.

Summarize this post with: