JSP and JSTL Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 3.09, 2006

Using Cookies

Part:   1  2  3  4  5 

JSP/JSTL Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Using Cookies

Using JavaBean Classes

HTTP Response Header Lines

Non ASCII Characters

JSTL and Expression Language

File Upload

Execution Context

JSP Elements

JSP Standard Tag Libraries (JSTL)

JSP Custom Tag

... Table of Contents

This chapter describes:

  • What Is Cookie?
  • Sending and Receiving Cookies
  • Persistent Cookies
  • Dumping HTTP Response with Cookies

What Is Cookie?

Cookie: A small amount of information sent by a Web server to a Web browser, saved by the browser, and sent back to the server later. Cookies are transmitted inside the HTTP header.

Cookies move from server to browser, and back to server as follows:

Web         Web         Local       Web           Web
Server      Browser     System      Browser       Server
Send        Receive     Save        Send back     Receive
cookies --> cookies --> cookies --> cookies   --> cookies

As you can see from the diagram, cookies are actually saved to the hard disk of Web browser user's machines. Many users are concerned about this. But I think it is pretty safe to allow your browser to save cookies.

If you are really concerned, you can change your browser's settings to reject cookies. But this may cause many Web based applications fail to run on your browser.

Sending and Receiving Cookies

Sending cookies to the browser can be done by the addCookie() method on the response object; while receiving cookies from the browser can be done by the getCookies() method on the request object. Here is program to demonstrate how to use those methods:

<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!--
 - CookieTest.jsp
 - Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
-->
<jsp:directive.page contentType="text/html"/>
<html><body>
<p>
<jsp:directive.page import="javax.servlet.http.Cookie"/>
<jsp:scriptlet><![CDATA[
   out.println("<b>Cookies received by the server:</b><br/>");
   Cookie[] cookies = request.getCookies();
   int n = 0;
   if (cookies!=null) {
      n = cookies.length;
      for (int i=0; i<cookies.length; i++) {
         out.println(cookies[i].getName()+": "
            +cookies[i].getValue()+"<br/>");
      }
   }
   out.println("<b>Cookies added by the server:</b><br/>");
   Cookie c = new Cookie("Cookie_"+n,"value");
   out.println(c.getName()+": "+c.getValue()+"<br/>");
   response.addCookie(c);
]]></jsp:scriptlet>
</p>
</body></html>
</jsp:root>

(Continued on next part...)

Part:   1  2  3  4  5 

Dr. Herong Yang, updated in 2006
JSP and JSTL Tutorials - Herong's Tutorial Notes - Using Cookies