Single logo
  • Courses
  • Articles
  • About
Join for freeJoin free
  1. Blog
  2. /
  3. S04L03 - Read and Write operation of Cookie in JSP and Servlets

JSP and Servlets Articles
0 views

S04L03 - Read and Write operation of Cookie in JSP and Servlets


May 14, 2025

Mastering Cookie Operations in JSP Servlets: A Comprehensive Guide

Table of Contents

  1. Introduction ............................................. 1
  2. Understanding Cookies .................... 2
  3. Setting Up Your JSP Servlet Project ............................................................ 3
  4. Writing Cookies in JSP Servlets .................................................................................... 4
  5. Reading Cookies in JSP Servlets .................................................................................... 6
  6. Best Practices for Cookie Management ............................................................ 8
  7. Conclusion ............................................... 10
  8. Additional Resources ......................... 11

Introduction

In the realm of web development, managing user data efficiently and securely is paramount. Cookies play a vital role in this process by allowing servers to store and retrieve user-specific information on the client's browser. This eBook delves into the intricacies of reading and writing cookies within JSP (JavaServer Pages) and Servlets, providing a step-by-step guide for beginners and developers with basic knowledge. By the end of this guide, you'll understand how to implement cookie operations effectively, enhancing user experience and maintaining session integrity.


Understanding Cookies

Cookies are small pieces of data stored on the client's browser, enabling web applications to remember information between different requests. They are essential for tasks such as session management, personalization, and tracking user behavior.

Key Concepts

  • Cookie Creation: The process of generating a cookie with a name, value, and optional attributes like expiration time.
  • Cookie Retrieval: Accessing cookies sent by the client's browser to the server during requests.
  • Session Management: Using cookies to maintain user sessions across multiple requests.

Advantages and Disadvantages

Advantages Disadvantages
Improves user experience Potential security risks (e.g., XSS)
Facilitates session management Limited storage capacity (~4KB per cookie)
Enables personalization Users can delete or block cookies

Use Cases

  • Authentication: Storing session IDs to verify user identity.
  • Preferences: Remembering user settings and preferences.
  • Tracking: Monitoring user behavior for analytics.

Setting Up Your JSP Servlet Project

Before diving into cookie operations, ensure your development environment is set up correctly.

Prerequisites

  • Java Development Kit (JDK): Ensure you have JDK installed.
  • Apache Tomcat: A widely used servlet container for deploying JSP and Servlets.
  • Integrated Development Environment (IDE): Tools like Eclipse or IntelliJ IDEA can streamline development.

Project Structure

A typical JSP Servlet project includes the following structure:

S04L03 - Read and Write Operation of Cookie in JSP Servlets/
│
├── src/
│   └── main/
│       ├── java/
│       │   └── org/studyeasy/SiteController.java
│       └── webapp/
│           ├── login.jsp
│           ├── member.jsp
│           └── WEB-INF/
│               └── web.xml
│
├── pom.xml
└── target/
    └── demo.war

Setting Up Your Environment

  1. Configure Apache Tomcat: Install and set up Tomcat to deploy your JSP Servlet application.
  2. Create Project Files: Set up your project structure as outlined above.
  3. Dependency Management: Use pom.xml for managing project dependencies with Maven.

Writing Cookies in JSP Servlets

Creating and sending cookies to the client's browser is a fundamental operation. Below is a step-by-step guide to writing cookies using JSP Servlets.

Creating a Cookie

To create a cookie, initialize a Cookie object with a name and value.

// Creating a new cookie named "username" with value "username"
Cookie cookie = new Cookie("username", "username");

Adding the Cookie to the Response

After creating the cookie, add it to the HTTP response to send it to the client's browser.

// Adding the cookie to the response
response.addCookie(cookie);

Complete Example: Writing a Cookie in SiteController.java

package org.studyeasy;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;

public class SiteController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Create a new cookie
        Cookie cookie = new Cookie("username", "username");
        
        // Add the cookie to the response
        response.addCookie(cookie);
        
        // Redirect to member.jsp
        response.sendRedirect("member.jsp");
    }
}

Explanation

  1. Cookie Initialization: A cookie named "username" with the value "username" is created.
  2. Adding to Response: The cookie is added to the response, which instructs the browser to store it.
  3. Redirection: After setting the cookie, the user is redirected to member.jsp.

Reading Cookies in JSP Servlets

Retrieving and processing cookies sent by the client's browser is equally important. Here's how to read cookies in JSP Servlets.

Accessing Cookies from the Request

Cookies are accessible via the HttpServletRequest object. Use the getCookies() method to retrieve them.

// Retrieving all cookies from the request
Cookie[] cookies = request.getCookies();

Iterating Through Cookies

Once retrieved, iterate through the cookies to find the desired one.

String username = null;
String sessionID = null;

// Check if cookies are not null
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("username")) {
            username = cookie.getValue();
        }
        if (cookie.getName().equals("JSESSIONID")) {
            sessionID = cookie.getValue();
        }
    }
}

Complete Example: Reading Cookies in member.jsp

<%@ page import="javax.servlet.http.Cookie" %>
<%
    String username = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();

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

    if (username == null || sessionID == null) {
        response.sendRedirect("login.jsp");
    }
%>




    Member Area


    

Member Area

Username: <%= username %>

Session ID: <%= sessionID %>

Explanation

  1. Importing Cookie Class: The Cookie class is imported for handling cookies.
  2. Retrieving Cookies: All cookies from the request are fetched.
  3. Iterating and Extracting Values: The code iterates through each cookie, extracting values for "username" and "JSESSIONID".
  4. Session Validation: If either username or sessionID is null, the user is redirected to the login page.
  5. Displaying Information: If valid, the username and session ID are displayed on the member area page.

Output Explanation

Upon successful login with correct credentials, the member.jsp displays:

Member Area
Username: username
Session ID: [Unique Session ID]

If incorrect credentials are provided, the user remains on the login page without redirection.


Best Practices for Cookie Management

Effective cookie management ensures security, performance, and a seamless user experience.

Security Considerations

  • Secure Flag: Ensure cookies are only sent over HTTPS by setting the Secure flag.
// Setting Secure flag
cookie.setSecure(true);

  • HttpOnly Flag: Prevent client-side scripts from accessing cookies by setting the HttpOnly flag.
// Setting HttpOnly flag
cookie.setHttpOnly(true);

  • SameSite Attribute: Mitigate CSRF attacks by setting the SameSite attribute.
// Setting SameSite attribute
cookie.setAttribute("SameSite", "Strict");

Managing Cookie Lifetime

  • Expiration Time: Set appropriate lifetimes for cookies based on their purpose.
// Set cookie to expire in one hour
cookie.setMaxAge(60 * 60);

Avoid Storing Sensitive Information

Never store sensitive data, such as passwords or personal information, in cookies. Instead, use session identifiers and server-side storage.

Limiting Cookie Size and Number

Browsers typically limit cookies to around 4KB each and a maximum number per domain. Keep cookies lightweight and limit their number to essential data only.

Regularly Clean Up Cookies

Implement mechanisms to remove obsolete or unnecessary cookies to maintain optimal performance and security.


Conclusion

Cookies are indispensable tools in web development, enabling personalized experiences and efficient session management. By mastering the techniques to read and write cookies in JSP Servlets, developers can enhance the functionality and security of their applications. This guide provided a comprehensive overview, from setting up your project to implementing best practices in cookie management. Embrace these strategies to build robust, user-friendly web applications that cater to the dynamic needs of today's internet users.

SEO Keywords: cookies in JSP Servlets, read and write cookies, JSP cookie management, servlet cookies, session management in JSP, secure cookie handling, Java web development, JSP tutorials, cookie operations in servlets, managing user sessions


Additional Resources

  • Official JSP Documentation
  • Apache Tomcat User Guide
  • OWASP Cookie Security
  • Java Servlet API
  • Maven Project Management

Note: This article is AI-generated.

Share Article

Back to Blog

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.