Home | | Internet Programming | Cookies - Java

Chapter: Web or internet Programming : Server Side Programming

Cookies - Java

A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.



A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking.


       Cookies were first introduced in Netscape Navigator.


       Version 2.0 of the Servlet API provides the javax.servlet.http.Cookie class for working with cookies. The HTTP header details for the cookies are handled by the Servlet API.


       create a cookie with the Cookie() constructor: public Cookie(String name, String value)

This creates a new cookie with an initial name and value.


A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse:

public void HttpServletResponse.addCookie(Cookie cookie)


This method adds the specified cookie to the response. Additional cookies can be added with subsequent calls to addCookie() . Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.


The code to set a cookie looks like this:


Cookie cookie = new Cookie("ID", "123");



A servlet retrieves cookies by calling the getCookies() method of HttpServlet-Request: public Cookie[] HttpServletRequest.getCookies()


This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:


Cookie[] cookies = req.getCookies();

if (cookies != null) {


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

String name = cookies[i].getName();

String value = cookies[i].getValue();





Session tracking using persistent cookies


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

import javax.servlet.http.*;


public class ShoppingCartViewerCookie extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {


res.setContentType("text/html"); PrintWriter out = res.getWriter();


// Get the current session ID by searching the received cookies.

String sessionid = null;


Cookie[] cookies = req.getCookies(); if (cookies != null) {

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


if (cookies[i].getName().equals("sessionid")) {

sessionid = cookies[i].getValue();








// If the session ID wasn't sent, generate one.


//  Then be sure to send it to the client with the response.


//  if (sessionid == null) {

sessionid = generateSessionId();


Cookie c = new Cookie("sessionid", sessionid); res.addCookie(c);



out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>"); out.println("<BODY>");


//  Cart items are associated with the session ID

//  String[] items = getItemsFromCart(sessionid);


// Print the current cart items.


out.println("You currently have the following items in your cart:<BR>");

if (items == null) { out.println("<B>None</B>");




else { out.println("<UL>");


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

out.println("<LI>" + items[i]);






// Ask if they want to add more items or check out.

out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>"); out.println("Would you like to<BR>");


out.println("<INPUT TYPE=submit VALUE=\" Add More Items \">"); out.println("<INPUT TYPE=submit VALUE=\" Check Out \">"); out.println("</FORM>");


// Offer a help page.


out.println("For help, click <A HREF=\"/servlet/Help" + "?topic=ShoppingCartViewerCookie\">here</A>");





private static String generateSessionId() {


String uid = new java.rmi.server.UID().toString();

// guaranteed unique return java.net.URLEncoder.encode(uid);

// encode any special chars



private static String[] getItemsFromCart(String sessionid) {

// Not implemented




Persistent cookies offer an elegant, efficient, easy way to implement session tracking. Cookies provide as automatic an introduction for each request as you could hope for. For each request, a cookie can automatically provide a client's session ID or perhaps a list of the client's preferences. In addition, the ability to customize cookies gives them extra power and versatility.


Advantages of cookies:


1. Cookies do not require any server resources since they are stored on the client. 2. Cookies are easy to implement.


3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).




       The biggest problem with cookies is that browsers don't always accept cookies. Sometimes this is because the browser doesn't support cookies.

       Due to limited memory space WAP gateways doesn‘t use cookies.

       Any intruder (unauthorized person) using client‘s machine can change value of cookies.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : Server Side Programming : Cookies - Java |

Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.