by Dinesh Thakur Category: Session And Cookies

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 http://localhost: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 http://localhost:8080/ReadCookies in the browser. It will display the output shown in Figure

           Retrieving Cookies





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.