Module 04
Module 04
Study Material
By
Faculty Name:
Mrs. Rajani,Vijayalakshmi B
Designation: Assistant Professor
Semester: VI
Module 4
Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development; A simple Servlet; The
Servlet API; The Javax.servlet Package; Reading Servlet Parameter; The Javax.servlet.http package;
Handling HTTP Requests and Responses; Using Cookies; Session Tracking. Java Server Pages (JSP):
JSP, JSP Tags, Tomcat, Request String, User Sessions, Cookies, Session Objects
https://www.redbooks.ibm.com/redbooks/pdfs/sg245755.pdf
Applet-Introduction
https://www3.ntu.edu.sg/home/ehchua/programming/java/J4c_AppletWebstart.html
Servlets Background
Servlets are small programs that execute on the server side of a web connection.
Applets dynamically extend the functionality of a web browser, servlets dynamically extend the
functionality of a web server.
This module focuses on the core concepts, interfaces, and classes, and simple programs on servlets
Servlets need the understanding of how web browsers and servers cooperate to provide content to a
user.
Consider a request for a static web page. A user enters a Uniform Resource Locator (URL) into a
browser. The browser generates an HTTP request to the appropriate web server.
The web server maps this request to a specific file. That file is returned in an HTTP response to the
browser.
The HTTP header in the response indicates the type of the content.
The Multipurpose Internet Mail Extensions (MIME) are used for this purpose.
Ex: The Hypertext Markup Language (HTML) source code of a web page has a MIME type of
text/html.
The dynamic web pages generate contents to reflect the latest information.
In the early days of the Web, a server could dynamically construct a page by creating a separate process
to handle each client request. The process would open connections to one or more databases in order
to obtain the necessary information. It communicated with the web server via an interface known as
the Common Gateway Interface (CGI).
CGI allowed the separate process to read data from the HTTP request and write data to the HTTP
response.
CGI suffered serious performance problems. It was expensive in terms of processor and memory
resources to create a separate process for each client request. It was also expensive to open and close
database connections for each client request. In addition, the CGI programs were not platform-
independent. Therefore, other techniques were introduced. Among these are servlets.
Servlets offer several advantages in comparison with CGI.
First, performance is significantly better. Servlets execute within the address space of a web server. It
is not necessary to create a separate process to handle each client request.
Second, servlets are platform-independent because they are written in Java.
Third, the Java security manager on the server enforces a set of restrictions to protect the resources on
a server machine.
Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms.
The Life Cycle of a Servlet
Three methods are central to the life cycle of a servlet.
These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server.
Consider a typical user scenario to understand when these methods are called.
First, assume that a user enters a Uniform Resource Locator (URL) to a web browser.
The browser then generates an HTTP request for this URL.
This request is then sent to the appropriate server.
Second, this HTTP request is received by the web server.
The server maps this request to a particular servlet.
The servlet is dynamically retrieved and loaded into the address space of the server.
Third, the server invokes the init( ) method of the servlet.
This method is invoked only when the servlet is first loaded into memory.
It is possible to pass initialization parameters to the servlet so it may configure itself.
Fourth, the server invokes the service( ) method of the servlet.
This method is called to process the HTTP request.
It is possible for the servlet to read data that has been provided in the HTTP request.
It may also formulate an HTTP response for the client.
The servlet remains in the server’s address space and is available to process any other HTTP requests
received from clients. The service( ) method is called for each HTTP request. Finally, the server may
decide to unload the servlet from its memory. The algorithms by which this determination is made are
specific to each server. The server calls the destroy( ) method to relinquish any resources such as file
handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory
allocated for the servlet and its objects can then be garbage collected.
Using Tomcat for Servlet Development
A servlet development environment is needed to create servlets and Tomcat is considered for the same.
Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software
Foundation.
It contains the class libraries, documentation, and run-time support that is needed to create and test
servlets.
The examples, consider the Windows OS environment. Version of Tomcat used is 5.5.17 is
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
If Tomcat is loaded in a different location, appropriate changes need to be made to the examples.
An environmental variable JAVA_HOME has to be set to the top-level directory in which the Java
Development Kit is installed.
To start Tomcat, select Configure Tomcat in the Start | Programs menu, and then press Start in the
Tomcat Properties dialog.
When experimentation is done with servlets, Tomcat can be stopped by pressing Stop in the Tomcat
Properties dialog.
The directory
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\
contains servlet-api.jar. This JAR file contains the classes and interfaces that are needed to build
servlets.
(jar - Java Archive, similar to zip files, it’s an aggregation of many files into one.)
To make this file accessible, update your CLASSPATH environment variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar
Alternatively, this file can be specified when servlets are compiled.
Ex:
javac HelloServlet.java -classpath "C:\Program Files\Apache Software Foundation\
Tomcat 5.5\common\lib\servlet-api.jar"
Once the servlet is compiled, Tomcat must be able to find it, which will be done, by copying the file
into a directory under Tomcat’s webapps directory and entering its name into a web.xml file.
To make it simple, the directory and web.xml file that Tomcat supplies for its own example servlets
can be used.
Here is the procedure that is to be followed.
First, copy the servlet’s class file into the following directory:
C:\Program Files\Apache Software Foundation\
Tomcat 5.5\webapps\servlets-examples\WEB-INF\classes
Next, add the servlet’s name and mapping to the web.xml file in the following directory:
C:\Program Files\Apache Software Foundation\
Tomcat 5.5\webapps\servlets-examples\WEB-INF
For instance, assuming the first example, called HelloServlet, add the following lines in the section
that defines the servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
Next, add the following lines to the section that defines the servlet mappings.
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
pw.close();
}
}
Program imports the javax.servlet package.
This package contains the classes and interfaces required to build servlets.
Next, the program defines HelloServlet as a subclass of GenericServlet.
The GenericServlet class provides functionality that simplifies the creation of a servlet.
For example, it provides versions of init( ) and destroy( ), which may be used as is. Only the service(
) method has to be implemented.
Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden.
This method handles requests from a client.
The first argument is a ServletRequest object. This enables the servlet to read data that is provided via
the client request.
The second argument is a ServletResponse object. This enables the servlet to formulate a response for
the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the
MIME type is text/html. This indicates that the browser should interpret the content as HTML source
code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the
client as part of the HTTP response.
Then println( ) is used to write some simple HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the proper Tomcat directory. Also,
add HelloServlet to the web.xml file, as described earlier.
Start Tomcat
Tomcat must be running before a servlet is executed.
Start a Web Browser and Request the Servlet
Start a web browser and enter the URL as below:
http://localhost:8080/servlets-examples/servlet/HelloServlet
Alternatively, URL can be entered as below:
http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine.
Output of the servlet will be seen in the browser display area, which will contain the
string Hello! in bold type.
The Servlet API
Two packages contain the classes and interfaces that are required to build servlets.
These are javax.servlet and javax.servlet.http. They constitute the Servlet API.
These packages are not part of the Java core packages. Instead, they are standard extensions provided
by Tomcat. Therefore, they are not included with Java SE 6.
The following table summarizes the core classes that are provided in the javax.servlet package:
The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These are
invoked by the server.
The getServletConfig( ) method is called by the servlet to obtain initialization parameters.
A servlet developer overrides the getServletInfo( ) method to provide a string with useful information
(for example, author, version, date, copyright). This method is also invoked by the server.
The ServletConfig Interface
The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The
methods declared by this interface are summarized here:
A default constructor is defined. It also defines the print( ) and println( ) methods, which output data
to the stream.
The ServletException Classes
javax.servlet defines two exceptions.
The first is ServletException, which indicates that a servlet problem has occurred.
The second is UnavailableException, which extends ServletException, which indicates that a servlet
is unavailable.
Reading Servlet Parameters
The ServletRequest interface includes methods that allows to read the names and values
of parameters that are included in a client request.
A servlet will be developed to illustrate its use.
The implementation contains two files.
A web page is defined in PostParameters.htm
A servlet is defined in PostParametersServlet.java.
The HTML source code for PostParameters.htm defines a table that contains two labels and two text
fields.
One of the labels is Employee and the other is Phone. There is also a submit button.
Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to
process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/
servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
The following table summarizes the core classes that are provided in this package.
The most important of these is HttpServlet.
Servlet developers can extend this class in order to process HTTP requests.
The names and values of cookies are stored on the user’s machine. Some of the information
that is saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie
The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration
date is not explicitly assigned to a cookie, it is deleted when the current browser session ends.
Otherwise, the cookie is saved in a file on the user’s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request.
If the user enters a URL whose domain and path match these values, the cookie is then supplied to the
Web server. Otherwise, it is not.
There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor. The
methods of the Cookie class are summarized in the table.
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
It defines a form that contains a select element and a submit button. The action parameter of the form
tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.
The source code for ColorGetServlet.java is shown in the following listing. The doGet( ) method is
overridden to process any HTTP GET requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by
the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}}
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml.
Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
After completing these steps, the browser will display the response that is dynamically generated by
the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that
is sent to the web server. Assume that the user selects the red option and submits the form.
The URL sent from the browser to the server is
http://localhost:8080/servlets-examples/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
Handling HTTP POST Requests
A servlet that handles an HTTP POST request is developed here. The servlet is invoked
when a form on a web page is submitted.
The example contains two files. A web page is defined in ColorPost.htm, and a servlet is defined in
ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing.
<html>
<body>
<center>
<form name="Form1"method="post"
action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
It is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies
that the POST method should be used, and the action parameter for the form tag specifies a different
servlet.
The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is
overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter(
) method of HttpServletRequest to obtain the selection that was made by the user. A response is then
formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
NOTE: Parameters for an HTTP POST request are not included as part of the URL that is sent
to the web server. In this example, the URL sent from the browser to the server is
http://localhost:8080/servlets-examples/servlet/ColorPostServlet.
The parameter names and values are sent in the body of the HTTP request.
Using Cookies
A servlet will be developed to illustrate the use of cookies.
The HTML source code for AddCookie.htm is shown in the following listing. This page contains a
text field in which a value can be entered.
There is also a submit button on the page. When this button is pressed, the value in the text field is sent
to AddCookieServlet via an HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet"> <B>Enter a
value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for AddCookieServlet.java is shown in the following listing.
It gets the value of the parameter named “data”.
It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data”
parameter.
The cookie is then added to the header of the HTTP response via the addCookie( ) method. A feedback
message is then written to the browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Any Java declaration statement can be used in a JSP tag. Multiple declaration statements can be placed
within a JSP tag by extending the close JSP tag to another line.
Ex:
<html>
<head>
<title>Variable declaration</title>
</head>
<body>
<%! int age=29;
float salary;
int empnumber;
%>
</body>
</html>
Other than variables, objects, arrays and Java collections can also be declared within a JSP tag.
<html>
<head>
<title>Variable declarations</title>
</head>
<body>
<%! String Name;
String [ ] Telephone = {"201-555-1212", "201-555-4433"};
String Company = new String();
Vector<String> Assignments = new Vector<String>( );
int [ ] Grade = {100,82,93};
%>
</body>
</html>
Above JSP program creates 3 String objects, an array and a vector.
Methods
A method is defined similar to a method definition in a Java program, except the method definition is
placed within a JSP tag.
Ex:
<html>
<head>
<title>Methods</title>
</head>
<body>
<%! int grade (int gr)
{
return gr + 10;
}
%>
<P> Grade is : <%= grade(80) %> </P>
</body>
</html>
The method is called from within the JSP extension tag that is enclosed within the HTML paragraph
tag.
The JSP virtual engine resolves the JSP tag that calls the method by replacing the JSP tag with the
results returned by the method, which is then passed along to the browser that called the JSP program.
Overloaded method in JSP
<html>
<head>
<title>Function overloading</title>
</head>
<body>
<%! int print (int gr)
{ return gr; }
String print(String gr)
{ return gr; }
%>
<P>Numerical value is : <%= print(80)%> </P>
<P>String value is : <%= print("RNS")%> </P> </body> </html>
Control Statements
The most powerful features available in JSP is the ability to change the flow of the program to create
dynamic content for a web page based on conditions received from the browser.
There are two control statements used to change the flow of JSP program.
If and switch
The code segment that is executed or skipped may consist of HTML tags or a combination of HTML
tags and JSP tags, or Java statements or Java tags.
Ex:
<html>
<head>
<title>If and Switch</title>
</head>
<body>
<%! int grade = 90; %>
<% if (grade > 69) { %>
<P> You passed </P>
<%} else { %>
<P> Better luck next time. </P>
<% } switch(grade) {
case 90: %>
<P> Your final grade is a A </P>
<% break;
case 80: %>
<P> Your final grade is a B </P>
<% break;
case 70 : %>
<P> Your final grade is a C </P>
<% break;
}%>
</body>
</html>
If statement requires 3 JSP tags, first contains the beginning of the if statement, including the
conditional expression. Second contains the else statement, and the third has the closed brace used to
terminate the else block.
Two HTML paragraph tags contain information that the browser displays, depending on the evaluation
of the conditional expression in the if statement. Only one of the HTML paragraph tags and related
information are sent to the browser.
Switch statement also is divided into several JSP tags because each case statement requires an HTML
paragraph tag and related information.
Loops
Looping constructs used in JSP are similar to the ones that are present in Java language, except HTML
tags and related information.
Three types of looping construct exist, namely for, while and do..while loop.
Loops play an important role in JSP database programs because loops can be used to populate HTML
tables with data in the result set.
Ex:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%! int [ ] grade = {100, 82, 93};
int x=0;
%>
<table>
<tr>
<td> First</td>
<td> Second</td>
<td> Third</td>
</tr>
<tr>
<% for(int i=0;i<3;i++) { %>
<td> <%=grade[i]%> </td>
<% }%>
</table>
<table>
<tr>
<td> First</td>
<td> Second</td>
<td> Third</td>
</tr>
<tr>
<% while (x<3) { %>
<td> <%=grade[x]%> </td>
<% x++; } %>
</tr>
</table>
<table>
<tr>
<td> First</td>
<td> Second</td>
<td> Third</td>
</tr>
<tr>
<% x=0;
do { %>
<td> <%=grade[x] %> </td>
<% x++;
} while (x<3); %>
</tr>
</table>
</body>
</html>
Above JSP code depicts a routine used to populate 3 HTML tables with values assigned to an array.
All the tables appear the same, although a different loop is used to create each table.
First table is created using a for loop. The opening table row tag <tr> is entered into the program before
the loop begins. This is because the for loop is only populating columns and not rows.
A pair of HTML table data cell tags <td> are placed inside the for loop along with a JSP tag that
contains an element of the array. JSP tag resolves to the value of the array element by the JSP virtual
program.
The close table row </tr> tag and the close </table> tag are inserted into the program following the
brace that closes the for loop block. These tags terminate the construction of the table.
Tomcat
JSP programs are executed by a JSP virtual machine that runs on a web server.
JBuilder is an IDE to execute JSP programs using JSP virtual machines.
One of the most widely used JSP virtual machines is Tomcat.
In addition to all these JDK is needed to execute JSP programs.
Request String
The browser generates a user request string whenever the submit button is selected.
The user request string consists of the URL and the query string.
http://www.jimkeogh.com/jsp/myprogram.jsp?fname="Bob"&lname="Smith"
Program has to parse the query string to extract values of fields that are to be processed by the program.
Query string can be processed by using methods of the JSP request object.
The getParameter(Name) is the method used to parse a value of a specific field.
The getParameter( ) method requires an argument, which is the name of the field whose value has to
be retrieved.
If the value of fname and name has to be retrieved from the previous URL, the statements of JSP
program are as follows.
<%! String Firstname = request.getParameter(fname);
are multiple instances of the field name, each with a different value.
The getParamterValues( ) method is used to return multiple values from the field specified as the
argument to the getParamterValues( ).
Ex:
<p><strong>Select your favorite species of flamingo. You may control-click
(Windows) or command-click (Mac) to select more than one.</strong></p>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){%>
<P> <%= a[i]%> </P>
<%}}
%>
<html>
<body>
<form action="test.jsp" method="get">
In the above example the selection list field values are retrieved. The name of the selection list field is
“multiple”, the values of which are copied into an array of String objects called “a”.
Elements of the array are then displayed in JSP expression tags.
Parsing Other Information
The request string sent to the JSP by the browser is divided into 2 general components that are separated
by the question mark.
Ex: https://www.google.com/search?q=request…
URL component appears to the left of the question mark and the query string is to the right of the
question mark.
Query string is made up of field names and values which are parsed using request object methods.
URL is divided into 4 parts, first is the protocol, which defines the rules that are used to transfer the
request string from the browser to the JSP program. Three of the more commonly used protocols are
HTTP, HTTPS and FTP
Next is the host and port combination. The host is the Internet Protocol (IP) address or name of the
server that contains the JSP program. The port number is the port that the host monitors.
Usually the port is excluded from the request string whenever HTTP is used because the assumption is
the host is monitoring port 80.
Ex: localhost:/8080
Following the host and port is the virtual path of the JSP program. The server maps the virtual path to
the physical path.
Ex: http://www.jimkeogh,com/jsp/myprogram.jsp
http is protocol
www.jimkeogh.com is the host
There is no port because the browser assumes that the server is monitoring port 80.
/jsp/myprogram.jsp is the virtual path.
User Sessions
A JSP program must be able to track a session as a client moves between HTML and JSP pages.
There are 3 commonly used methods to track a session.
1) By using a hidden field
2) By using a cookie
3) By using a JavaBean
A hidden field is a field in an HTML form whose value is not displayed on the HTML page.
Ex:
<INPUT TYPE="hidden" NAME="userID" VALUE="123">
Page 273 text book 2
A value can be assigned to an hidden field in a JSP program before the program sends the dynamic
HTML page to the browser.
Ex:
Assume a JSP database system displays a dynamic login screen. The browser sends the user
ID and password to the JSP program, when the submit button is selected, where these parameters are
parsed and stored into two memory variables
JSP program then validates the login information and generates another dynamic HTML page
once the user ID and password are approved. The new dynamically built HTML page contains a form
that contains a hidden field, among other fields and the userID is assigned as the value to the hidden
field.
When the user selects the submit button on the new HTML page, the userID stored in the hidden
field and information in other fields on the form are sent by the browser to another JSP program for
processing.
This cycle continues where the JSP program processing the request string receives the userID
as a parameter and then passes the userID to the next dynamically built HTML page as a hidden field.
In this way, each HTML page and the subsequent JSP program has access to the userID and hence can
track the session.
Cookies
A cookie is a small piece of information created by a JSP that is stored on the client’s hard disk by the
browser
Cookies are used to store various kinds of information, such as user preferences and an ID that tracks
a session with a JSP database system.
A cookie can be created and read by using methods of the Cookie class and the response object
Ex: Creation of cookie using JSP
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%! String MyCookieName = "userID";
String MyCookieValue = "JK1234";%>
<% response.addCookie(new Cookie(MyCookieName, MyCookieValue));
%>
</body>
</html>
Above html code creates and writes a cookie called userID that has a value of JK1234.
The program begins by initializing the cookie name and cookie value and then passes these String
objects as arguments to the constructor of a new cookie.
This cookie is then passed to the addCookie( ) method, which causes the cookie to be written to the
client’s hard disk.
Ex: Retrieval of cookie using JSP
<html>
<head>
<title> JSP Programming> </title>
</head>
<body>
<%! String MyCookieName="userID", MyCookieValue,CName,CValue;
int found=0; %>
if (MyCookieName.equals(CName)) {
found=1;
MyCookieValue = CValue;
}
}
if (found == 1) { %>
<P> Cookie name = <%= MyCookieName %> </P>
<P> Cookie value = <%= MyCookieValue %> </P>
<% }%>
</body>
</html>
The above HTML code retrieves a cookie and sends the cookie name and cookie value to the browser,
which displays these on the screen.
The program begins by initializing the MyCookieName String object to the name of the cookie that
needs to be retrieved from the client’s hard disk, termed as userID.
Two other String objects are created to hold the name and value of the cookie read from the client, an
int variable “found” is created and initialized to zero. This variable is used as a flag to indicate whether
or not the userID cookie is read.
Next an array of Cookie objects called cookies is created and assigned the results of the
request.getCookies( ) method, which reads all the cookies from the client’s hard disk and assigns them
to the array of Cookies objects.
The program proceeds to use the getName( ) and getValue( ) methods to retrieve the name and value
from each object of the array of Cookie objects. Each time a Cookie object is read, the program
compares the name of the cookie to the value of the MyCookieName String object, which is userID.
When a match is found, the program assigns the value of the current Cookie object to the
MyCookieValue String object and changes the value of the found variable from 0 to 1.
After the program reads all the Cookie objects, the program evaluates the value of the found variable.
If the value is 1, the program sends the value of MyCookieName and MyCookieValue to the browser,
which displays these values on the screen.
Session Objects
A JSP database system is able to share information among JSP programs within a session by using a
session object.
Each time a session is created, a unique ID is assigned to the session and stored as a cookie.
The unique ID enables JSP programs to track multiple sessions simultaneously while maintaining data
integrity of each session.
Session ID is used to prevent the intermingling of information from clients.
In addition to session ID, a session object is also used to store other types of information called
attributes. An attribute can be login information, preferences or even purchase placed in an electronic
shopping cart.
Session attributes can be retrieved and modified each time a JSP program runs.
Ex: to assign information to a session attribute.
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%! String AtName = "Product",AtValue="1234"; %>
<% session.setAttribute(AtName, AtValue); %>
</body>
</html>
Two string objects are created and initialized. One string object is assigned the name of the attribute
and the other is assigned a value for the attribute. setAttribute( ) method is called and these values are
passed to it.