• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Servlet » Session » Servlet to create cookies and add them to the response header
Next →
← Prev

Servlet to create cookies and add them to the response header

By Dinesh Thakur

One of the ways to keep track of session between the client and the server is through the use of cookies. A cookie is a piece of information that a web server sends to the browser.

The web server assigns a unique ID as a cookie to each client. It sends the cookie to the client by embedding it in the response header. With each request, the client sends this cookie value to the server. Using this value, the server identifies the user. Cookie is usually used to maintain the information about the client (such as user ID, name, etc.) that is needed every time a client visits the website. A cookie is constructed using the following constructor of Cookie class. public Cookie(String name, String val)

A servlet to create cookies and add them to the response header

import java.io.* ;

import javax.servlet.*;

import javax.servlet.http.*;

public class CreateCookies extends HttpServlet

{

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

   {

       Cookie name = new Cookie(“name”, request.getParameter(“name”));

       // Create cookie for name

       Cookie age= new Cookie(“age”, request.getParameter(“age”));

       // Create cookie for age

       name.setMaxAge(60*60*12); //60*60*24

       age.setMaxAge(60*60*12); // 60*60*24

       // Set expiry date after 12 Hrs for both the cookies

       response.addCookie(name);

       response.addCookie(age);

       // Add both the cookies in the response header

       response.setContentType(“text/html”);

       // Set response content type

       PrintWriter out= response.getWriter();

       String title = “Example to Set Cookies”;

       out.println(“<html>\n” +”<head><title>” + title+

       “</title></head>\n” +”<body >\n” +

       “<h1 align=\”center\”>” + title + “</h1>\n” +

       “<ul>\n” + “<li><b>Name</b>: “

       + request.getParameter(“name”) + “\n” +

       ” <li><b>Age</b>: “

       + request.getParameter(“age”) + “\n” +

       “</ul>\n” + “</body></html>”);

    }

}

This example creates two cookies using the Cookie () constructor. First one is name having the name “name” and the value of the “name” parameter. Other one is age having the name “age” and value of the “age” parameter. The maximum age of both the cookies is set to 12 hrs; the browser will keep this cookie information for 12 hrs. These cookies are then added to the HTTP response header using addCookie () method.

HTML code to call the servlet named CreateCookies is as follows:

<HTML>

   <BODY>

      <FORM ACTION=”servlet/CreateCookies” METHOD=” GET”>

            Name: <INPUT TYPE=”text” NAME=”name”>

      <BR/>

            Age: &nbsp;&nbsp;&nbsp;<INPUT TYPE=”text” NAME=”age” />

             <BR><BR>

              <INPUT TYPE=”submit” VALUE=”Submit” />

      </FORM>

    </BODY>

</HTML>

Compile the servlet CreateCookies and create appropriate entry in web.xml file. Type the URL https://ecomputernotes.com:8080/CreateCookies in the browser. It will display the output shown in Figure

          Web Page Displaying the form

Enter the Name and Age, and then click the submit button on the web page. It will display the output and set two cookies named name and age, which will be passed to the server every time when the submit button is clicked.

        Output Generated by CreateCookies Servlet

A servlet to retrieve cookies from the HTTP request header

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ReadCookies extends HttpServlet

{

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException

   {

        Cookie cookie = null;

        Cookie[] cookies= null;

        cookies= request.getCookies();

        // Get an array of Cookies

        response.setContentType(“text/html”);

        // Set response content type

        PrintWriter out= response.getWriter();

        String title = ” Example to Read Cookies”;

        out.println(“<html>\n” +”<head><title>” + title+

        “</title></head>\n” +”<body>\n” );

        if( cookies !=null )

          {

              out.println(“<h2> Cookies found: Name and Value</h2>”);

              for (int i = 0; i < cookies.length; i++)

                   {

                        cookie= cookies[i];

                        out.print(“Name : “+cookie.getName( )+”, “);

                        out.print(“Value: “+cookie.getValue( )+”<br/>”);

                   }

           }

                  else

                      {

                          out.println(“<h2>No cookies exist</h2>”);

                      }

                          out.println(“</body>”);

                          out.println(“</html>”);

     }

}

In this example, the cookies that are included in the HTTP request header are retrieved by calling getcookies () method of HttpServletRequest object.. This method returns an array of cookie objects for the current request. The name and value associated with each cookie is obtained using the getName () and get Value () methods respectively. The names and values of these cookies are then written to HTTP response.

Compile the servlet ReadCookies and create appropriate entry in web.xml file. Type the URL https://ecomputernotes.com:8080/ReadCookies in the browser. It will display the output shown in Figure

           Retrieving Cookies

You’ll also like:

  1. Response Status Code in Servlet.
  2. Session Tracking Using Cookies
  3. Steps for Sending Cookies
  4. Reading Cookies from the Client
  5. Advantages and Disadvantages of Cookies
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

SQL Tutorials

SQL Tutorials

  • SQL - Home
  • SQL - Select
  • SQL - Create
  • SQL - View
  • SQL - Sub Queries
  • SQL - Update
  • SQL - Delete
  • SQL - Order By
  • SQL - Select Distinct
  • SQL - Group By
  • SQL - Where Clause
  • SQL - Select Into
  • SQL - Insert Into
  • SQL - Sequence
  • SQL - Constraints
  • SQL - Alter
  • SQL - Date
  • SQL - Foreign Key
  • SQL - Like Operator
  • SQL - CHECK Constraint
  • SQL - Exists Operator
  • SQL - Drop Table
  • SQL - Alias Syntax
  • SQL - Primary Key
  • SQL - Not Null
  • SQL - Union Operator
  • SQL - Unique Constraint
  • SQL - Between Operator
  • SQL - Having Clause
  • SQL - Isnull() Function
  • SQL - IN Operator
  • SQL - Default Constraint
  • SQL - Minus Operator
  • SQL - Intersect Operator
  • SQL - Triggers
  • SQL - Cursors

Advanced SQL

  • SQL - Joins
  • SQL - Index
  • SQL - Self Join
  • SQL - Outer Join
  • SQL - Join Types
  • SQL - Cross Join
  • SQL - Left Outer Join
  • SQL - Right Join
  • SQL - Drop Index
  • SQL - Inner Join
  • SQL - Datediff() Function
  • SQL - NVL Function
  • SQL - Decode Function
  • SQL - Datepart() Function
  • SQL - Count Function
  • SQL - Getdate() Function
  • SQL - Cast() Function
  • SQL - Round() Function

Other Links

  • SQL - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW