Adv Java Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Advanced Java Programming 21CS642

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

Tomcat home page URL


https://tomcat.apache.org/tomcat-7.0-doc/deployer-howto.html

Servlets - Important sites


https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html

https://www.redbooks.ibm.com/redbooks/pdfs/sg245755.pdf

JSP beginners book


https://beginnersbook.com/2013/11/jsp-implicit-object-session-with-examples/

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.

Dept of CSE,KSIT Page 1


Advanced Java Programming 21CS642

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.
Dept of CSE,KSIT Page 2
Advanced Java Programming 21CS642

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

Dept of CSE,KSIT Page 3


Advanced Java Programming 21CS642

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.

Dept of CSE,KSIT Page 4


Advanced Java Programming 21CS642

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>

Same general procedure must be followed for all of the examples.

*************

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.

Create and Compile the Servlet Source Code


To begin, a file named HelloServlet.java must be created that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{

public void service(ServletRequest request, ServletResponse response)


Dept of CSE,KSIT Page 5
Advanced Java Programming 21CS642

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.

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.
Dept of CSE,KSIT Page 6
Advanced Java Programming 21CS642

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 javax.servlet Package


The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.

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:

Dept of CSE,KSIT Page 7


Advanced Java Programming 21CS642

The Servlet Interface


All servlets must implement the Servlet interface.

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.

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

Dept of CSE,KSIT Page 8


Advanced Java Programming 21CS642

The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The
methods declared by this interface are summarized here:

Dept of CSE,KSIT Page 9


Advanced Java Programming 21CS642

The ServletContext Interface


The ServletContext interface enables servlets to obtain information about their environment.
Several of its methods are summarized in the table.

The ServletRequest Interface


The ServletRequest interface enables a servlet to obtain information about a client request.
Several of its methods are summarized in the table.

Dept of CSE,KSIT Page 10


Advanced Java Programming 21CS642

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for a client. Several
of its methods are summarized in the table.

The GenericServlet Class


The GenericServlet class provides implementations of the basic life cycle methods for a servlet.

GenericServlet implements the Servlet and ServletConfig interfaces.

In addition, a method to append a string to the server log file is available.

The signatures of this method are shown here:


void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.

The ServletInputStream Class


The ServletInputStream class extends InputStream.
It is implemented by the servlet container and provides an input stream that a servlet developer
can use to read the data from a client request.

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.

Dept of CSE,KSIT Page 11


Advanced Java Programming 21CS642

The ServletOutputStream Class


The ServletOutputStream class extends OutputStream.
It is implemented by the servlet container and provides an output stream that a servlet developer
can use to write data to a client response.

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"
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 source code for PostParametersServlet.java is as follows.

The service( ) method is overridden to process client requests.

The getParameterNames( ) method returns an enumeration of the parameter names.


These are processed in a loop.

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 {

Dept of CSE,KSIT Page 13


Advanced Java Programming 21CS642

// Get print writer.


PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}

The javax.servlet.http Package


The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers.

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.

Dept of CSE,KSIT Page 14


Advanced Java Programming 21CS642

The HttpServletRequest Interface

Dept of CSE,KSIT Page 15


Advanced Java Programming 21CS642

The HttpServletRequest interface enables a servlet to obtain information about a client


request. Several of its methods are shown in the table.

The HttpServletResponse Interface


The HttpServletResponse interface enables a servlet to formulate an HTTP response to a
client.

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.

Dept of CSE,KSIT Page 16


Advanced Java Programming 21CS642

Several methods of this interface are summarized in the table.

The HttpSession Interface


The HttpSession interface enables a servlet to read and write the state information that is
associated with an HTTP session.

Several of its methods are summarized in the table. All of these methods throw an
IllegalStateException if the session has already been invalidated.

Dept of CSE,KSIT Page 17


Advanced Java Programming 21CS642

The HttpSessionBindingListener Interface


The HttpSessionBindingListener interface is implemented by objects that need to be notified
when they are bound to or unbound from an HTTP session.

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.

The Cookie Class


The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information. Cookies are valuable for tracking user activities.

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.

Dept of CSE,KSIT Page 18


Advanced Java Programming 21CS642

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.

Dept of CSE,KSIT Page 19


Advanced Java Programming 21CS642

The HttpServlet Class


The HttpServlet class extends GenericServlet. It is commonly used when developing servlets
that receive and process HTTP requests.
The methods of the HttpServlet class are summarized in the table.

Dept of CSE,KSIT Page 20


Advanced Java Programming 21CS642

The HttpSessionEvent Class


HttpSessionEvent encapsulates session events. It extends EventObject and is generated when
a change occurs to the session.

It defines this constructor:


HttpSessionEvent(HttpSession session)
Here, session is the source of the event.

HttpSessionEvent defines one method, getSession( ):


HttpSession getSession( )
It returns the session in which the event occurred.

The HttpSessionBindingEvent Class

Dept of CSE,KSIT Page 21


Advanced Java Programming 21CS642

The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener


is bound to or unbound from a value in an HttpSession object.

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( )

Handling HTTP Requests and Responses


The HttpServlet class provides specialized methods that handle the various types of HTTP
requests. A servlet developer overrides one of these methods.

These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).

The GET and POST requests are commonly used when handling form input.

Handling HTTP GET Requests


A servlet will be developed which handles an HTTP GET request.

The servlet is invoked when a form on a web page is submitted.

The example contains two files.

A web page is defined in ColorGet.htm, and a servlet is defined in ColorGetServlet.java.


Dept of CSE,KSIT Page 22
Advanced Java Programming 21CS642

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");

Dept of CSE,KSIT Page 23


Advanced Java Programming 21CS642

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>
Dept of CSE,KSIT Page 24
Advanced Java Programming 21CS642

<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.

Dept of CSE,KSIT Page 25


Advanced Java Programming 21CS642

Using Cookies
A servlet will be developed to illustrate the use of cookies.

The servlet is invoked when a form on a web page is submitted.


The example contains three files as summarized here:

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.

Dept of CSE,KSIT Page 26


Advanced Java Programming 21CS642

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

public class AddCookieServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

// Get parameter from HTTP request.


String data = request.getParameter("data");

// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);

// Add cookie to HTTP response.


response.addCookie(cookie);

// Write output to browser.


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);

pw.close();
}
}

The source code for GetCookiesServlet.java is shown in the following listing.

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.

getName( ) and getValue( ) methods are called to obtain this information.

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

public class GetCookiesServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
Dept of CSE,KSIT Page 27
Advanced Java Programming 21CS642

// Get cookies from header of HTTP request.


Cookie[] cookies = request.getCookies();

// Display these cookies.


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}

<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.

A session can be created via the getSession( ) method of HttpServletRequest.


An HttpSession object is returned by this method.
This object can store a set of bindings that associate names with objects.

Dept of CSE,KSIT Page 28


Advanced Java Programming 21CS642

The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods


of HttpSession manage these bindings.

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.*;

public class DateServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null)
pw.print("Last access: " + date + "<br>");
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);}
Dept of CSE,KSIT Page 29
Advanced Java Programming 21CS642

Java Servlet Pages (JSP)


JSP is a server-side program that is similar in design and functionality to a java servlet.

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.

Dept of CSE,KSIT Page 30


Advanced Java Programming 21CS642

jspDestroy( ) method is identical to the destroy( ) method in a Java servlet.


destroy( ) is automatically called when the JSP terminates normally. This method will not be
called if the JSP abruptly terminates (when server crashes).
destroy( ) method is used for cleanup where resources used during the execution of the JSP are
released, such as disconnecting from a database.

service( ) method is automatically called and retrieves a connection to HTTP.

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.

Declaration statement tag


This tag opens with <%! and is followed by a Java declaration statement that defines variables,
objects and methods that are available to other components of the JSP program.

Directive tags

Dept of CSE,KSIT Page 31


Advanced Java Programming 21CS642

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.

taglib tag specifies a file that contains a tag library.


Ex:
<%@ page import=" import java.sql.*"; %>
<%@ include file="keogh\books.html" %>
<%@ taglib url="myTags.tld" %>

First tag imports java.sql package.


Second tag includes the books.html located in the keogh directory.
Last tag loads the myTags.tld library.

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 %>.

Variables and Objects


Declaration of variables and objects are similar to Java programs, except that they must appear
as a JSP tag within the JSP program before the variable or object is used in the program.

A simple JSP program is shown below.


<html>
<head>
<title>Printing value of a variable</title>
</head>
<body>
<%! int age=29; %>
<P> Your age is: <%=age%> </P>
Dept of CSE,KSIT Page 32
Advanced Java Programming 21CS642

</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

<%! 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>
Dept of CSE,KSIT Page 34
Advanced Java Programming 21CS642

</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>
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>

Dept of CSE,KSIT Page 37


Advanced Java Programming 21CS642

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.

Dept of CSE,KSIT Page 38


Advanced Java Programming 21CS642

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);
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.

response object is an instance of HttpServletResponse

session object is an instance of HttpSession

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

Dept of CSE,KSIT Page 39


Advanced Java Programming 21CS642

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");

Dept of CSE,KSIT Page 40


Advanced Java Programming 21CS642

if(a!=null)
{
for(int i=0;i<a.length;i++){%>
<P> <%= a[i]%> </P>
<%}}
%>

<html>
<body>
<form action="test.jsp" method="get">

<select name="multiple" multiple="multiple">


<option value="American">American flamingo</option>
<option value="Andean">Andean flamingo</option>
<option value="Chilean">Chilean flamingo</option>
<option value="Greater">Greater flamingo</option>
<option value="James's">James's flamingo</option>
<option value="Lesser">Lesser flamingo</option>
</select>

<input type="submit">
</form>
</body>
</html>

PROCEDURE
Save this test.jsp in webapp directory
And in browser type http://localhost:8080/test.jsp

Dept of CSE,KSIT Page 41


Advanced Java Programming 21CS642

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.

Dept of CSE,KSIT Page 42


Advanced Java Programming 21CS642

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.

Dept of CSE,KSIT Page 43


Advanced Java Programming 21CS642

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; %>
Dept of CSE,KSIT Page 44
Advanced Java Programming 21CS642

<% Cookie[] cookies = request.getCookies(); %>

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


CName = cookies[i].getName();
CValue = cookies[i].getValue();

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.

Dept of CSE,KSIT Page 45


Advanced Java Programming 21CS642

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.
Dept of CSE,KSIT Page 46
Advanced Java Programming 21CS642

Ex: to retrieve the attribute values


<%@ page import="java.util.*" %>
<html>
<head>
<title> JSP Programming </title>
</head>

<body>

<%! Enumeration purchase; String Atname; String Atvalue;%>


<% purchase=session.getAttributeNames(); %>

<% while (purchase.hasMoreElements()) {


Atname = (String)purchase.nextElement();
Atvalue = (String)session.getAttribute(Atname); %>
<P>Attribute name <%= Atname %> </P>
<P>Attribute value <%= Atvalue %> </P>
<% }%>

</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.

Dept of CSE,KSIT Page 47


Advanced Java Programming 21CS642

Dept of CSE,KSIT Page 48

You might also like