Pr.Pg Next Pg

Reading Cookies using Servlet tutorials

  • You can read any cookies sent by the browser from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods. 

  • HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.



Example: Servlet program to read cookies

Sam Sir

//Program name

// Program to read cookies




import javax.servlet.*;

import javax.servlet.http.*;


public class Readingcookies extends HttpServlet


protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


Cookie cookie = null;

Cookie[] cookies = null;

cookies = request.getCookies();




PrintWriter out = response.getWriter();

String title = “Reading Cookies Example”;

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

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

“<body bgcolor=\”#f0f0f0\”>\n” );

if( cookies != null ){

out.println(“<h2> Found Cookies 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/>”);




“<h2>No cookies founds</h2>”);







Reading cookies using Servlets

Pr.Pg border                                              Next Pg