Adv Java Module 4
Adv Java Module 4
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.
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.
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.
Dept of CSE,KSIT Page 2
Advanced Java Programming 21CS642
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.
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.
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
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
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.
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>
*************
A Simple Servlet
The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the
proper directory, and add the servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Program imports the javax.servlet package.
This package contains the classes and interfaces required to build servlets.
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.
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.
Dept of CSE,KSIT Page 6
Advanced Java Programming 21CS642
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.
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 interfaces that are provided in this package. The most
significant of these is Servlet. All servlets must implement this interface or extend a class that
implements the interface. The ServletRequest and ServletResponse interfaces are also very
important.
The following table summarizes the core classes that are provided in the javax.servlet package:
It declares the init( ), service( ), and destroy( ) methods that are called by the server during the
life cycle of a servlet.
A method is also provided that allows a servlet to obtain any initialization parameters. The
methods defined by Servletare shown in the table below.
The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These
are invoked by the server.
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 allows a servlet to obtain configuration data when it is loaded. The
methods declared by this interface are summarized here:
It defines the default constructor. In addition, a method is provided to read bytes from the
stream.
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset. The method returns
the actual number of bytes read or –1 if an end-of-stream condition is encountered.
A default constructor is defined. It also defines the print( ) and println( ) methods, which
output data to the stream.
The first is ServletException, which indicates that a servlet problem has occurred.
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"
Dept of CSE,KSIT Page 12
Advanced Java Programming 21CS642
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 parameter name and value are output to the client. The parameter value is obtained
via the getParameter( ) method.
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
This functionality makes it easy to build servlets that work with HTTP requests and responses.
The following table summarizes the core interfaces that are provided in this package:
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.
Several constants are defined. These correspond to the different status codes that can be
assigned to an HTTP response.
Ex: SC_OK indicates that the HTTP request succeeded, and
SC_NOT_FOUND indicates that the requested resource is not available.
Several of its methods are summarized in the table. All of these methods throw an
IllegalStateException if the session has already been invalidated.
The methods that are invoked when an object is bound or unbound are
void valueBound(HttpSessionBindingEvent e)
void valueUnbound(HttpSessionBindingEvent e)
Here, e is the event object that describes the binding.
Ex: Assuming that a user visits an online store. A cookie can save the user’s name, address,
and other information. The user does not need to enter this data each time he or she
visits the store.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the
HttpServletResponse interface. The data for that cookie is then included in the header of
the HTTP response that is sent to the browser.
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.
It is also generated when an attribute is bound or unbound. Here are its constructors:
HttpSessionBindingEvent(HttpSession session, String name)
HttpSessionBindingEvent(HttpSession session, String name, Object val)
Here, session is the source of the event, and name is the name associated with the object that is
being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.
The getName( ) method obtains the name that is being bound or unbound.
String getName( )
The getSession( ) method, obtains the session to which the listener is being bound or unbound:
HttpSession getSession( )
The getValue( ) method obtains the value of the attribute that is being bound or unbound.
Object getValue( )
These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).
The GET and POST requests are commonly used when handling form input.
The HTML source code for ColorGet.htm is shown in the following listing.
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<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.
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>
Dept of CSE,KSIT Page 24
Advanced Java Programming 21CS642
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.
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 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.*;
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
pw.close();
}
}
It invokes the getCookies( ) method to read any cookies that are included in the HTTP GET
request.
The names and values of these cookies are then written to the HTTP response.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<html>
<body>
<center>
<form name="Form1"
method="get"
action="http://localhost:8080/cookies/GetCookiesServlet">
<input type=submit value="Submit">
</form>
</body>
</html>
method=”get” because we are retrieving cookie value from the client side to server for display
purpose.
Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one.
In some applications it may be necessary to save state information so that information can be
collected from several interactions between a browser and a server. Sessions provide such a
mechanism.
It is important to note that session state is shared among all the servlets that are associated with
a particular client.
The following servlet illustrates the usage of session state.
The getSession( ) method gets the current session. A new session is created if one does not
already exist.
The getAttribute( ) method is called to obtain the object that is bound to the name “date”.
Date object encapsulates the date and time when the current page was last accessed.
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name “date” to this object.
Ex:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
JSP will be called by a client to provide a web service, the nature of which depends on the J2EE
(Java 2 Enterprise Edition) application.
JSP processes the request (by using logic built into the JSP or by calling other web components
built using Java servlet technology or created using other technologies), and responds by
sending the results to the client.
JSP differs from a Java servlet in the way in which the JSP is written.
Java servlet is coded using the Java programming language and responses are encoded as an
output String object that is passed to the println( ) method. The output String object is
formatted in HTML, XML or the format required by the client.
JSP is coded in HTML, XML or in the client’s format that is interlaced with scripting elements,
directives and actions composed of Java programming language and JSP syntax.
JSP can be used as a middle-level program between clients and web services.
JSP
JSP is simpler to create than a Java servlet, because JSP is coded in HTML rather than with the
Java programming language.
JSP provides the same features found in a Java servlet because a JSP is converted to a Java
servlet the first time a client requests the JSP.
There are 3 methods that are automatically called when a JSP is requested and when JSP
terminates normally. These are jspInt( ) method, the jspDestroy( ) method and the service( )
method. These methods can be overridden.
jspInt( ) method and jspDestroy( ) methods are commonly overridden in a JSP to provide
customized functionality, when JSP is called and terminates.
jspInt( ) method is identical to the init( ) method in a Java servlet and in an applet.
jspInt( ) method is called when the JSP is requested and is used to initialize objects and
variables that are used throughout the life of JSP.
JSP Tags
A JSP program consists of a combination of HTML tags and JSP tags.
JSP tag defines Java code that is to be executed before the output of the JSP program is sent to
the browser.
A JSP tag begins with <%, which is followed by Java code and ends with %>.
JSP tags are embedded into the HTML component of a JSP program and are processed by a
JSP virtual engine such as Tomcat. Tomcat reads the JSP program, whenever the program is
called by a browser and resolves JSP tags, then sends the HTML tags and related information
to the browser.
Java code associated with JSP tags in the JSP program is executed when encountered by
Tomcat, and the result of that process is sent to the browser. Browser is aware of displaying
the result because the JSP tag is enclosed within an open and closed HTML tag.
There are 5 types of JSP tags in a JSP program, which are as follows.
Comment tag
A comment tag opens with <%-- and closes with --%> and is followed by a comment that
usually describes the functionality of statements that follow the comment tag.
Directive tags
This tag opens with <%@ and commands the JSP virtual engine to perform a specific task,
such as importing a Java package required by objects and methods used in a declaration
statement. Directive tag closes with %>.
There are 3 commonly used directives, which are import, include and taglib.
import tag is used to import java packages into the JSP program.
include tag inserts a specified file into the JSP program replacing the include tag.
Expression tags
This tag opens with <%= and is used for an expression statement whose result replaces the
expression tag when the JSP virtual engine resolves JSP pages. This tag closes with %>.
Scriptlet tags
This tag opens with <% and contains commonly used Java control statements and loops. A
scriptlet tag closes with %>.
</body>
</html>
Program declares an int called age and initializes the variable with value 29, and the declaration
statement is placed within the JSP tag (which begins with <%!.
This tag conveys to JSP virtual engine to make statements contained in the tag available to
other JSP tags in the program. This tag has to be used for all variables and objects if it has to
be used throughout the program.
The variable age is used in an expression tag that is embedded within the HTML paragraph tag
<P>. A JSP expression tag begins with <%=, which is followed by the depression.
JSP virtual engine resolves JSP expression before sending the output of the JSP program to the
browser.
Ex: JSP tag <%=age%> is replaced with the number 29, afterwards, the HTML paragraph tab
and related information is sent to the browser.
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>
Dept of CSE,KSIT Page 33
Advanced Java Programming 21CS642
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.
</head>
<body>
<%! int print (int gr)
{ return gr; }
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>
Dept of CSE,KSIT Page 35
Advanced Java Programming 21CS642
<% 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>
Dept of CSE,KSIT Page 36
Advanced Java Programming 21CS642
<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.
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.
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);
String Lastname = request.getParameter(lname);
%>
The first statement uses the getParameter( ) method to copy the value of fname from the request
string and assign that value to the Firstname object.
The second statement performs a similar function, but using the value of the name from the
request string.
There are 4 predefined implicit objects that are in every JSP program.
These are request, response, session and out.
request object’s getParameter( ) method can be used to retrieve elements of the request string.
request object is an instance of the HttpServletRequest.
out object is an instance of the JspWriter that is used to send a response to the client.
Page 390
https://www.java4s.com/java-servlet-tutorials/example-on-getparametervalues-method-of-
servlet-request/
Copying a value from a multivalued field such as a selection list field is difficult, because there
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>
if(a!=null)
{
for(int i=0;i<a.length;i++){%>
<P> <%= a[i]%> </P>
<%}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<input type="submit">
</form>
</body>
</html>
PROCEDURE
Save this test.jsp in webapp directory
And in browser type http://localhost:8080/test.jsp
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”.
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.
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.
<body>
<%! String MyCookieName="userID", MyCookieValue,CName,CValue;
int found=0; %>
Dept of CSE,KSIT Page 44
Advanced Java Programming 21CS642
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.
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.
<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.
Dept of CSE,KSIT Page 46
Advanced Java Programming 21CS642
<body>
</body>
</html>
The above program reads attributes, program begins by calling the getAttributeNames( )
method that returns names of all the attributes as an Enumeration.
Program checks whether or not the getAttributeNames( ) method returns any attributes. If so,
statements within the while loop execute, which assigns the attribute name of the current
element to the Atname String object.
Atname string object is then passed as an argument to the getAttribute( ) method, which returns
the value of the attribute. The value is assigned to the Atvalue String object. Program then
sends the attribute name and value to the browser.