You are on page 1of 139

J2EE Servlets & JSP

===========================================================================================================================

Chapter: 1
JAVA AND THE J2EE PLATFORM

Topics Discussed

 Introduction
 Enterprise Today
 System Architecture
2-Tier Architecture
3-Tier Architecture
n-Tier Architecture
Enterprise Architecture
 Is Java the Answer?
Platform Independence
Reusability
Modularity
 The J2EE Platform
 J2EE Architecture – Containers

1.1 Introduction

Java, as a programming language is still young. However, the evolution of Java


from a means of developing applets for running in browsers, to a programming
model capable of driving today’s’ enterprise applications has been remarkable.
Java has been around for only five years, yet it has attracted a very high level of
interest in the technical and business communities, fuelling a considerable range
of applications.

From its inception, Java has triggered new programming models and technologies
in different domains – ranging from devices, to telephony applications, to the
enterprise. At the same time, Java has acted as a catalyst in making certain
technology domains take more robust and secure shapes. Java’s enterprise
computing platform, a.k.a. the Java 2 Platform, Enterprise Edition (J2EE) is
one such domain.

There were times in the history of Java, when debates on whether Java is a
programming language or a platform used to surface in the media as well as
technical circles. However, J2EE is one of the most successful attempts by Sun
and its associates at making Java credible as a platform for enterprise computing.

But what is J2EE? Why is it relevant? Why should you choose this technology for
building enterprise-level application – from client-server to Internet to mobile?
This chapter gives one perspective, and assists you in answering these questions.
We hope that the rest of this book will help you to successfully build and manage
such applications.

In this introductory chapter, we’ll focus on

 The J2EE technical architecture

1
J2EE Servlets & JSP

===========================================================================================================================
 What makes J2EE credible as a platform

 What are the challenges it addresses

 What technologies constitute the J2EE platform

First however, let us start with the challenges of developing applications for the
enterprise today.

1.2 The Enterprise Today

With the advent of the Internet, many businesses realized that a whole new
market had opened up to be exploited, however, we doubt if many had realized
what a radical effect it would have on the economy. Through the Internet and the
recent growth of e-commerce, an organization’s information assets have now
become more valuable. This shift to an information economy is forcing many
businesses to rethink even their most basic business practices. In order to
maintain a competitive edge, the adoption of new technologies has become a key
factor in a company’s ability to best exploit its information assets. More
importantly, adapting these new technologies to work in tandem with the
existing, legacy systems has become one of the foremost requirements of the
enterprise.

One place these shifts in business practices have been felt most keenly is at the
application development level. The funding and the time allocated to application
development have been shrinking, while demands for complexity have increased.
Although the emphasis on information is a small hurdle for developers, the whole
revolution is being driven by the rapidly changing technological and economic
landscape, which has created some new challenges for today’s enterprise
application developers:

 Responsiveness
Although timeliness has always been important, the high-placed, fast-
changing information-driven economy means that responding quickly to
new directions and information is critical in establishing and maintaining a
competitive edge.

 Programming Productivity
Direct adoption of new technologies is insufficient unless they are properly
utilized to their full potential and appropriately integrated with other
relevant technologies. Thus, the ability to develop and then deploy
applications as effectively and as quickly as possible is also important.
Achieving this can be complicated by the sheer variety of technologies and
standards that have been developed over the years, requiring highly
developed skill sets, the acquiring of which and keeping up with which is a
problem in itself. Moreover, the rapid pace of change in `standards’
themselves poses significant challenges to ensuring efficient meshing of
technologies.

 Reliability and Availability


In today’s Internet economy downtime can be fatal to the success of a
business. The ability to get your web-based operations up and running,
and to keep them running, is critical to success. As if that wasn’t’ enough,
you must also be able to guarantee the reliability of your business
transactions so that they will be processed completely and accurately.

2
J2EE Servlets & JSP

===========================================================================================================================

 Security
The Internet has not only exponentially increased the number of potential
users but also the value of a company’s information, thus the security of
that information has become of prime concern. What’s more as
technologies become more advanced, applications more sophisticated, and
enterprises more complex, the ability to implement an effective security
model become increasingly difficult.

 Scalability
The ability for the application to grow to meet new demand both in its
operation and user base is important when an application’s potential user
base may be millions of individual users through the Internet. To scale
effectively requires not only the ability to handle a large increase in the
number of clients but also effective use of system resources.

 Integration
Although information has grown to be a key business asset, much of this
information exists as data in old and outdated information systems. In
order to maximize the usefulness of this information, applications need to
be able to integrate with the existing information system – not necessary
an easy task as current technologies have often advanced far ahead of
some of these legacy systems. The ability to combine old and new
technologies is key to the success of developing for today’s enterprises.

None of these problem domains is especially new to the enterprise developer! But
solving these problems in a comprehensive and economical manner is still crucial.
You may be aware that there have been several technologies to address one or
more of the above demands. However, what has been missing is a
comprehensive platform with a rich infrastructure and numerous architectural
possibilities that also promotes a rapid development environment.

1.3 System Architecture

When discussing enterprise application development, it is appropriate to introduce


the concept of n-tier architecture. Typical client/server systems are based on
the 2-tiered architecture, whereby there is a clear separation between the data
and the presentation/business logic. These are generally data driven, with the
application existing entirely on the client machine while the database server is
deployed somewhere in the organization. While this approach allows us to share
data across the enterprise, it does have many drawbacks.

1.3.1 2-Tier Architecture

In a traditional 2-tiered application, the processing load is given to the client PC


while the server simply acts as a traffic controller between the application and the
data. As a result, not only does the application performance suffer due to the
limited resources of the PC, but the network traffic tends to increase as well.
When the entire application is processed on a PC, the application is forced to
make multiple requests for data before even presenting anything to the user.
These multiple database requests can heavily tax the network.

3
J2EE Servlets & JSP

===========================================================================================================================

Application

DB

Another problem, with a 2-tiered approach is that of maintenance. Even the


smallest of changes to an application might involve a complete rollout to the
entire user base. Even if it’s possible to automate the process, you are still faced
with updating every single client installation. What’s more, some users may not
be ready for a full rollout and ignore the changes while another group insists on
making the changes immediately. This can result in different client installation
using different versions of the application.

1.3.2 3-Tier Architecture

To address these issues, the software community developed the notion of a 3-tier
architecture. An application is broken up into three separate logical layers, each
with a well-defined set of interfaces. The first tier is referred to as the
presentation layer and typically consists of a graphical user interface of some
kind. The middle tier, or business layer, consists of the application or business
logic and the third tier – the data layer – contains the data that is needed for the
application.

The middle tier (application logic) is basically the code that the calls upon
(through the presentation layer) to retrieve the desired data. The presentation
layer then receives the data and formats it for display. The separation of
application logic from the user interface adds enormous flexibility to the design of
the application. Multiple user interfaces can be built and deployed without ever
changing the application logic, provided the application logic presents a clearly
defined interface to the presentation layer.

The third tier contains the data that is needed for the application. This data can
consist of any source of information, including an enterprise database such as
Oracle or Sybase, a set of XML documents (data that has been stored in
documents conformant to the XML specification), or even a directory service like
an LDAP server. In addition to the traditional relational database storage
mechanism, there are many different sources of enterprise data that your
applications can access.

4
J2EE Servlets & JSP

===========================================================================================================================

User Interface

Application
Logic

XML
Document
DB s

However, we’re not quite finished with our subdivision of the application. We can
take the segregation one final step to create an n-tier architecture.

1.3.3 n-Tier Architecture

As the title suggests, there is no hard and fast way to define the application
layers for an n-tier system. In fact, an n-tier system can support a number of
different configurations. In an n-tier architecture the application logic is divided
by function rather than physically.

n-tier architecture then breaks down like this:

 A user interface that handles the user’s interaction with the application;
this can be a web browser running through a firewall, a heavier desktop
application or even a wireless device

 Presentation logic that defines what the user interface displays an dhow
a user’s request are handled – depending own hat user interfaces are
supported you may need to have slightly different versions of the
presentation logic to handle the client appropriately

 Business logic that models the application’s business rules, often through
the interaction with the application’s data.

 Infrastructure services that provide additional functionality required by


the application components, such as messaging, transactional support,
etc.

 The data layer where the enterprise’s data resides.

5
J2EE Servlets & JSP

===========================================================================================================================

Browser

Firewall

Application Client

Presentation Logic

Business Logic
Service

XML
Document
DB s

Applications based on this architecture are employing the Model-View-


Controller (MVC) pattern. What this ultimately means is that the data (the
model) is separated from how the information is presented (the view). In
between this is the application/business logic (the controller) that controls the
flow of the information. Therefore, an application is designed based on these
three functional components (model, view, and controller) interacting with each
other.

1.3.4 Enterprise Architecture

So far we have really been concentrating on a single application’s architecture,


however, we are in danger of considering these application as ‘stovepipes”. In
other words, we might end up with many different applications – possibly even
with different architectures – all of which don’t communicate with one another. In
an enterprise, we are looking to create a more cohesive whole.

Rather than a change in architecture – enterprise architecture is basically just n-


tier – we need a change in perception. To turn an n-tier system into an enterprise
system, we simply extend the middle tier by allowing for multiple application
objects rather than just a single application. These application objects must cash
have an interface that allows it to work together with the others.

An interface can be thought of as a contract. Each object states through its


interface that it will accept certain parameters and return a specific set of results.
Application objects communicate with each other using their interfaces:

6
J2EE Servlets & JSP

===========================================================================================================================

HTML Form HTML Form HTML Form

Interface Interface Interface


Application Application Application
component component component

Database Middleware

XML
Remote Systems DB Document
s

With enterprise architecture, we can have multiple applications using a common


set of components across an organization. This promotes the standardization of
business practices by creating a single set of business functions for the entire
organizations to access. If a business rule changes, then changes have to be
made to the business object only and, if necessary, it’s interface and
subsequently any object that accesses the interface.

It is important to note that when designing an object and its interface, it is


a good idea to make the interface as generic as possible to avoid changes
later on. Since other objects communicate with the interface and not the
object itself, changes to the object, and not the interface, are relatively
simple and quick.

1.4 Is Java the Answer?

So far we have discussed system architecture from an implementation agnostic


perspective and there exist many potential paths that you can take to actually
implement your enterprise. Microsoft has Windows DNA (and the new.net
architecture), Sun has J2EE, Oracle has the Oracle 8i Internet Platform, and so
on. With so many choices for server-side development, you are probably
wondering what makes Java such a great choice.

1.4.1 Platform Independence

7
J2EE Servlets & JSP

===========================================================================================================================

With a enterprise’s information spread disparately across many different


platforms and applications it is important to leverage a programming
language that can work equally well throughout the enterprise without having
to resort to awkward, inefficient translation mechanisms. A unifying
programming model also reduces the difficulties encountered from
integrating many of the different technologies that grow up specific to certain
platforms and applications.

1.4.2 Reusability

Code reuse is the holy grail of all programming. Segregating an application’s


business requirements into component parts is one way to achieve reuse; using
object-orientation to encapsulate shared functionality is another. Java uses both.
Java is an object-oriented language and, as such, provides mechanisms for reuse.
However, unlike objects, components require a more complex infrastructure for
their construction and management. Basic object oriented concepts do not
provide such a framework; however, the Enterprise Edition of Java provides a
significantly stringent architecture for the reuse of components.

1.4.3 Modularity

When developing a complete server-side application, your programs can get large
and complex in a hurry. It is always best to break down an application into
discreet modules that are each responsible for specific task. When you do this, it
makes your application much easier to maintain and understand Java servlets,
JavaServer Pages, and Enterprise JavaBeans provide ways to modularize your
application - breaking your application down into tiers and into tasks.

Despite the above features in its favor, it was not until early 2000 that Java
developed a unifying programming model for applications on the enterprise scale
– not that it lacked the capabilities but rather it was disorganized. Sun recognized
this shortcoming and released the Java 2 Platform, Enterprise Edition (J2EE).

The idea behind the J2EE platform is to provide a simple, unified standard
for distributed applications through a component-based application
model.

1.5 The J2EE Platform

As you’ll see in the rest of this book, J2EE is one of the best solutions that we’ve
had so far for meeting the demands of today’s enterprise. J2EE specifies both the
infrastructure for managing your applications, and the service APIs for building
them.

The J2EE platform is essentially a distributed application server environment – a


Java environment that provides the following:

 A runtime infrastructure for hosting applications.


 A set of Java extension APIs to build applications

The applications that you can develop with the above may be programs to drive
web pages, or components to implement complex database transaction, or even
Java applets – all distributed across the network.

8
J2EE Servlets & JSP

===========================================================================================================================

1.6 J2EE Architecture – Containers

As discussed in the previous section, a typical commercial J2EE platform includes


one or more containers. But what’s a container? A J2EE container is a runtime to
manage application components, and to provide access to the J2EE, APIs. Beyond
the identity associated with the runtime, J2EE does not specify any identity for
containers. This gives a great amount of flexibility to achieve a variety of features
within the container runtime.

This architecture shows two containers:

 A web container for hosting Java servlets and JSP pages

 An EJB container for hosting Enterprise JavaBean components

Apart from these two, the J2EE also specifies two more containers - an
applet container to run applets, and an application client container for
running standard Java application clients. In this book, our focus is limited
to web and EJB containers only.

In the above figure, the vertical blocks at the bottom of each container represent
the J2EE APIs. Apart from access to these infrastructure-level APIs, each
container also implements the respective container-specific API (Java Servlet API
for the web container, and the EJB API for the EJB container).

The stacks of rectangles (servlets, JSP pages, and EJBs) in this figure are the
programs that you develop and host in these containers. In the J2EE parlance,
these programs are called application components.
The following figure shows the architecture of J2EE.

Web Container EJB Container

Application Java Servlets


Clients Enterprise
JavaBeans
JSP Panes

RMI/IIOP,JNDI,JTA, RMI/IIOP,JNDI,JTA,
JDBC,JMS,javaMail, JDBC,JMS,javaMail,
JAF JAF

J2EE Application Server

Databases and
Other Resources

9
DB
J2EE Servlets & JSP

===========================================================================================================================

So we can also say that a container is a Java 1.2 (Java 2 Standard Edition
1.2) runtime for application components.

In this architecture, there are primarily two types of clients.

 Web clients normally run in web browsers. For these clients, the user
interface is generated on the server side as HTML or XML, and is
downloaded and then rendered by the browsers. These clients use HTTP to
communicate with web containers. Application components in web
containers include Java servlets and JSP pages. These components
implement the functionality required for web clients. Web containers are
responsible for accepting requests from web clients, and generating
responses with the help of the application components.

 EJB clients are applications that access EJB components in EJB


containers. There are two possible types of EJB clients. The first category
is application clients. Application clients are stand-a-alone applications
accessing the EJB components using the RMI-HOP protocol. The second
category of application clients is components in the web container. That is,
Java servlets and JSP pages can also access the EJB components via the
RMI-HOP protocol in the same way as the application clients.

In either case, clients access application components via the respective container.
Web clients access JSP pages and Java servlets via the web container, and EJB
clients access the EJB components via the EJB container.

10
J2EE Servlets & JSP

===========================================================================================================================

Chapter: 2

SERVLETS

Topics Discussed

 Introduction to Servlets
 Why use Servlets?
 Resources for Writing Servlet
 The Servlet Architecture
 Servlet Lifecycle
 Creating a Simple Servlet
 Development Phases of J2EE Applications
 Development Phases of J2EE Applications
 The Servlet API
 Handling HTTP Requests

2.1 Introduction to Servlets

The evolution of Internet has led to the development of the Java language. It
serves as a complete client/server solution where programs are dynamically
downloaded onto the client. Till date, the focus has been on the client-side
development of applets and GUI components, which is incomplete as far as client-
server computing is concerned. Therefore, in this chapter, you will be introduced
to the other side of the client/server computing – the Servlets.

Servlets are programs that run on a Web server and build Web pages on the fly.
Building Web pages on the fly is useful (and commonly done) for a number of
reasons:

• The Web page is based on data submitted by the user. For example the
results pages from search engines are generated this way, and programs that
process orders for e-commerce sites do this as well.
• The data changes frequently. For example, a weather-report or news
headlines page might build the page dynamically, perhaps returning a
previously built page if it is still up to date.
• The Web page uses information from corporate databases or other
such sources. For example, you would use this for making a Web page at an
on-line store that lists current prices and number of items in stock.

A servlet can be thought of as a server-side applet. Servlets are loaded and


executed by a Web server in the same manner as the applets are loaded and
executed by a Web browser. A servlet accesses requests from the client,
performs some task, and returns results.
The following are the basic steps of using servlets:
• The client makes a request.
• The Web server forwards the request to the servlet after receiving it from the
client.
• Some kind of process is done by the servlet after receiving the request.

11
J2EE Servlets & JSP

===========================================================================================================================
• A response is returned back to the web server from the servlet.
• The web server will forward the response to the client.

Figure 2.1 shows how a web server processes a request and the response sent to
the client.
Request
Web Server
Client
Servlet
Response

Fig. 2.1
Working of a servlet

The security issues, as associated with applets, are not applied with servlets
because servlets are executed on the server and if you Web server is secure
behind a firewall, then your servlets is secure as well.

2.2 Why use Servlets?

Servlets have various benefits over other technologies that are used for writing
server side programs. One such technology is CGI (Common Gateway Interface)
scripts. Servlets have less start-up cost, they run continuously, and they are
platform-independent. The following section distinguishes between Servlets and
CGI-based Web programs in detail.

The CGI program that handles the request for the server is terminated as soon as
the request is processed whereas Servlets continue to run even after the request
is processed. This eliminates the heavy start-up overhead. The CGI program must
store the information in a database or a file and read it again the next time it
starts up when it needs to maintain information across the network. There is
heavy start-up overhead for this reason.

You have to create different versions of plug-ins for running the same CGI
program on a different hardware platform or a different operating system.
Servlets can run on any platform that supports Java.

Different levels of security can be allowed for different servlets by taking


advantage of Java’s security framework. For example, a security policy, which
allows a servlet to access only certain directories on your file system, can be
defined. CGI programs do not have a basic security framework, but rely instead
of on a collection of ad hoc rules.

2.3 Resources for Writing Servlet

You have to install JavaSoft’s Java Servlet Development Kit (JSDK) before
creating any servlet. This kit includes the Java servlet and Sun servlet packages,
sample services for Windows 95 and NT, and ServletRunner to test servlets.

You have to set the environment variable CLASSPATH, to the required location so
that your servlets can find the servlet packages. The following environment
variable need to be set for Windows systems, with the JSDK installed in the
C:\2sdk:

Classpath: c:\j2sdk\j2sdk.jar;
Path: c:\j2sdk\bin;

12
J2EE Servlets & JSP

===========================================================================================================================

The JSDK can be downloaded from the JavaSoft home page


(http://java.sun.com). The Java Servlet Development Kit is included as a part of
JDK 1.2. If you are still using JDK 1.1 you should download the JSDK 1.0.1
separately.

To run Servlets, you need a Web server that supports the Servlet API. We will be
using J2EE (Java 2 Enterprise edition 1.2.1) to run servlets. There are various
other vendors that are providing server implementations for this purpose. Some
of them are given in Table 2.1.

Vendor Product
Apache Apache jserv
ATG Dynamo Application Server
Cybotics Cybotics Search Engine
IBM Internet Connection Server
KonaSoft KonaSoft Enterprise Server
Lotus Domino Go Webserver
Novocode NetForge Web Server
O’Reilly Website Professional
Tandem iTP Webserver
W3C Jigsaw HTTP Server
WebLogic Tengah Application Server

Table 2.1
List of products supporting Java Servlets

The following steps are required to run any servlet:

1. If your Web server is not running, start it.


2. Configure the Web server to install the servlet.
3. Run your browser.
4. Direct the browser to the particular URL that refers to the new servlet.

Another thing to remember while creating servlets is that you need to create
some kind of client application that invokes the servlet. This client application can
be provided in form of HTML or applets. We will be developing our applications
using HTML. While HTML is lightweight and is supported by Java enabled web
browsers, applets are beneficial as they solve the portability and distribution
problems. We will be using both HTML and applets to communicate with servlets.

2.4 The Servlet Architecture

There are various interfaces and classes that are used to implement a simple
servlet. Let us discuss some of them that are essential for working of a servlet.

The Servlet Interface

All servlets implement the Servlet interface, either directly or by extending a


class that implements it such as GenericServlet. The Servlet interface provides
methods that manage the servlet and its communications with clients. While
developing a servlet, you need to provide implementations for all or some of
these methods. For example, the init () and destroy() methods are used to start
and stop a servlet. The service() method is invoked by the server so that the
servlet can perform its services. It takes two parameters one of the
ServletRequest interface and the other of the ServletResponse Interface.

13
J2EE Servlets & JSP

===========================================================================================================================

Service/Response and ServletRequest Interface

When a servlet accepts a call from a client, it receives objects from the
ServletRequest and ServletResponse interfaces. The ServletRequest interface
encapsulates the communication from the client to the server, while the
ServletResonse interface encapsulates the communications from the servlet back
to the client.

The ServletRequest interface allows the servlet access to information such as the
names of the parameters passed in by the client, the protocol (scheme) being
used by the client, and the names of the remote host (getRemoteHost ()
method) that made the request and the server that received it. It also provides
the servlet with access to the input stream, ServletOutputStream, through
which the servlet gets data from clients that are using application protocols such
as the HTTP POST and PUT method. Subclasses of ServletRequest allow the
servlet to retrieve more protocol-specific data. For example,
HttpServletRequest contains methods for accessing HTTP-specific header
information.

The ServletResponse interface gives the servlet methods for replying to the
client. It allows the servlet to set the content length and mime type of the reply,
and provides an output stream, ServletOutputStream, and a Writer though which
the servlet can send the reply data. Subclasses of ServletResponse give the
servlet more protocol-specific capabilities. For example, HttpServletResponse
contains methods that allow the servlet to manipulate HTTP-specific header
information.

The classes and interfaces described above make up a basic Servlet. There are
various other methods that are used to give additional capabilities to a servlet. A
detailed explanation of these classes and interfaces is given later in the chapter.

2.5 Servlet Lifecycle

Servlets run on servers as we have discussed earlier. Let us now see how a
servlet is loaded and run on a web server. When a server loads a servlet, it runs
the servlet’s init method. The server calls the init method once, when it loads the
servlet, and will not call it again unless it is reloading the servlet.

The server cannot reload a servlet until after it has removed the servlet by calling
the destroy method. Initialization is allowed to complete before client requests
are handled (i.e. before the service method is called) or the servlet is destroyed.

After the server loads and initialize the servlet, the servlet is able to handle client
requests. It processes them in its service method. Each client’s request has its
call to the service method run in its own servlet thread: the method receives the
client’s request, and sends the client its response.

Servlets can run multiple service methods at a time.

Servlets run until they are removed from the service, for example, a request of a
system administrator. When a server removes a servlet, it runs the servlet’s
destroy method. The method is run once; the server will not run it again after it
reloads and reinitializes the servlet. The servlet lifecycle is given in Figure 2.2.

14
J2EE Servlets & JSP

===========================================================================================================================

Server Loa
d Server Code

Server Client
Code Handle Client
Requests
Server Client

Server Unload
Server Code

Fig. 2.2
The Servlet Lifecycle

2.6 Creating a Simple Servlet

The basic steps required for writing servlets are as follows:

• Step 1: Extend the GenericServlet class.


• Step 2: Override the service() method. (The init() and destroy() methods are
not overridden to make the program simpler. The init() and destroy()
methods are typically used when the program needs to initialize or release
some resources.)
• Step 3: Get the output stream from the ServletResponse object and create a
PrintStream object with it.
• Step 6: Finally, print the request string to the PrintStream.

Let us write a simple servlet program with the help of the above methods. This
servlet will respond to the client with the server’s information.

import java.io.*;
import javax.servlet.*;
public class SimpleServlet extends GenericServlet
{
public String getServletInfo( )
{
return "Localhost ";
}
public void service(ServletRequest req, ServletResponse res)
{
try {
PrintStream out = new PrintStream
(res.getOutputStream() );
out.println ("Hello "+ req.getRemoteHost());
out.println ("The following is the information about the
environment in which the servlet is running ");
out.println ("The name of the server running is
"+getServletInfo() );

15
J2EE Servlets & JSP

===========================================================================================================================
} catch (Exception e) {}
}
}

The above servlet extends the GenericServlet class and overrides the
getServletInfo() and the service() method. The getServletInfo() method returns a
string that provides information about the servlet. The service() method
implements the actual request handling and response handling. The Web server
invokes it when the URL of the servlet is requested. The server passes the
ServletRequest and ServletResponse arguments to the servlet. The
getRemoteHost() method returns the name of the host that made the request.

Save this file in the folder ServletExample. Compile it using the javac compiler as
given below:

C:\ServletExample> javac SimpleServlet.java

Now let us write the HTML, which will invoke this servlet. The HTML is given
below:

<html>
<head>
Servlet Example
</head>
<form Method = "GET" Action = "SimpleServletAlias" >
<INPUT NAME= "Test" Type=SUBMIT VALUE="test">
</input>
</form>
</html>

Save this file as Servlet.html in the folder ServletExample. The Action


attribute of the Form tag takes the alias name of the Servlet. This is the alias
name that should be provided while deploying the servlet using J2EE. We will see
this while assembling the servlet.

2.7 Development Phases of J2EE Applications

The servlet that is created will be assembled and run on a J2EE server. As a J2EE
application evolves, it passes through these development phases:

• Web Component Creation


• J2EE Application Client Creation
• J2EE Application Assembly
• J2EE Application Deployment

The first two stages are already accomplished. The web component i.e. the
servlet and the client application, i.e. the HTML file, have already been created.
Now let us look a next stage of developing a J2EE application. This involves J2EE
application Assembly and deployment. Figure 2.3 shows how a web component
can be assembled in a J2EE application (.ear file) and then deployed on the
server.

Assembly Deployment
Web J2EE J2EE Server
Phase Phase
Component Application
(.WAR file) (.ear file)

16
J2EE Servlets & JSP

===========================================================================================================================

Fig. 2.3
J2EE application assembly and deployment

• The Servlet API

The Servlet API was defined by Sun Microsystems for writing servlets. The
package javax.servlet defines all the classes and interfaces associated with the
Servlet SPI. Some of the interfaces defined inside the Servlet API are:

• Servlet
• ServletContext
• ServletRequest
• ServletResponse

And the classes are:

• ServletInputStream
• ServletOutputStream

To write servlets, the developer has to use the four interfaces to make the server
comply with the servlet API and then use the server’s implementations of this
interface along with the ServletInputStream, and ServletOutputStream
classes. The following section describes the Servlet API classes and interfaces in
detail.

The Servlet Interface and its Methods

The Servlet Interface allows the developer to create servlets by providing the
necessary functions. This interface includes the methods listed in Table 2.2:

Method Description
public void service( ServletRequest This method is used to service a single
req, ServletResponse res) request from a client. This main
purpose of the parameters is to access
the input and output streams that are
connected to the client browser.
public void init() This method is called by the system
when the servlet is first loaded. It is
basically used for general initialization
of the servlet. The init () method might
be called to reset the servlet after it
has been used. Hence, you have to be
careful that only initialization is
performed in this init () method.
ServletContext getServletContext() This method gets a servletContext
object that is associated with
information about the environment in
which the servlet is running.
ServletContext getServletContext() This method gets a servletContext
object that is associated with
information about the environment in
which the servlet is running.
void log (String mesg) This method is used to log a message
to the servlet log. Log is generally

17
J2EE Servlets & JSP

===========================================================================================================================
written into a directory called log under
the server’s home directory. These log
entries depict the accesses the Web
server receives.
String getServletInfo() This method returns the information
about the servlet, as a string.
Public void destroy() This method is used to release the
servlet.

Table 2.2
Servlet Interface Methods

• The ServletRequest Interface

The ServletRequest interface defines methods, gets input streams from the client,
collects the header information, and extracts path and query information from the
requested URL. The header information defines general aspects of the connection.
The precise set of headers will depend on the browser being used to issue the
request. You can get the header information through some methods described
later in this chapter. Table 7.3 lists the methods of this interface:

Method Description
int This method is used to return the size of the input data to
getContentLength() be supplied (in bytes). It returns –1 if the size is unknown.
String getContent This method is used to return a string that is associated with
Type() the MIME content type for the data that is to be sent to the
servlet from the client browser. This method returns nil if
the client has not specified the content type. The Content
type depends on the browser. For instance, some browsers
specify content types of text / plain to indicate that the
data is of no special type. Some use content / unknown,
and some use application / octet-stream.
String getProtocol() This method is used to return the protocol and version of a
Web browser client. The returned string is of the form
<Protocol/major-version>.<minor-version>.
String This method is used to return the value of the parameter
getParameter( String (Query string defined in the URL) associated with the name
parameter-name) of the parameter passed as an argument to this method. For
example, if an URL is given as;
http://localhost:8080/servlets/Myservlet>mesg=Hello,
the method call getParameter(“mesg”) would return the
string value Hello.
Enumeration This method is used to return an enumeration of strings
getParameterNames( representing the names of the parameters defined in the
) URL. This method does not return the values associated with
the parameters. To obtain the associated values, call the
getParameter() method.
InetAddress This method is used to return the IP address of the client
getRemoteAddr() who sent the request.
String This method is used to return the name of the host who
getRemoteHost() made the request.
String This method is used to return a string that represents only
getQueryString() the query string part of the Servlet URL.
String This method is used to return a string that represents the
getServerName() host name of the server.

18
J2EE Servlets & JSP

===========================================================================================================================
int getServerPort() This method is used to return an integer that represents the
port number through which the request is received.
String This method is used to return the path information that
getPathTranslated() describes the path on the server machine from which the
servlet was loaded.
String This method is used to return the header information
getHeader(String associated with the header_field. To obtain the header_field
header_field) use the method getParameterNames().
ServletInputStream This method returns the input stream for reading the
getInputStream() request data.
Table 2.3
ServletRequest Interface Methods

• The ServletResponse Interface

The ServletResponse interface methods that are used for getting an output
stream directed at the client, setting the header information, sending errors to
the client, and setting the status of the response. This interface allows you to
send information to the client’s browser.

The response status can be set through a list of static integer variables defined by
the ServletResponse interface. The following are the variables:

• SC_OK
• SC_CREATED
• SC_NO_CONTENT
• SC_MOVED_PERMANENTLY
• SC_MOVED_TEMPORARILY
• SC_BAD_REQUEST
• SC_UNAUTHORIZED
• SC_FORBIRDDEN
• SC_NOT_FOUND

Table below lists the methods of ServletResponse interface:

Method Description
ServletOutputStream This method is used to return the
getOutputStream() output stream for writing responses to
the client browser.
void setContentLength(int length) This method is used to set the content
length of the response.
void setContentType (String type) This method is used to set the content
type for the response. The content
types are the MIME types discussed
earlier. (Refer note for more details
about MIME).
void write-Headers() This method is used to write the status
and message headers for the response
to the output stream.
void setStatus (int status) This method is used to write the status
and message headers for the response
to the output stream.
void setStream (int status) This method is used to set the status
code and a default message for the
response.

19
J2EE Servlets & JSP

===========================================================================================================================
void setHeader( String header_field, This method is used to set the value of
String header_value) a header field.

Table 2.4
ServletResponse Interface Methods.

Note: The MIME Types area allows you to manage the list of suffixes and MIME
type mapping for the Web service. A MIME type is a way to determine the
contents of a file; thus you can map an extension (such as ` wav’ ) to a
particular MIME type (such as audio/x.wav) so that the Web service knows
what type of file is being handled. The format of MIME type is
Type/Subtype, which the file extension is mapped to. The type defines the
generic file category (such as audio, image, etc.) and the subtype defines
the exact type within the generic type (such as x-wav, jpeg, etc.).

• The ServletContext Interface


The ServletContext interface allows you to find out information about the
environment in which the servlet is running. Table 2.5 lists the methods through
which you can find these details;

Method Description
String getServerInfo() This method is used to return a string
that represents the name and the
version of the server running.
String getServlet() This method is used to return a string
that represents the name of the servlet.
Enumeration getServlets() This method used to return an
enumeration of all the available servlets
in this context.

Table 2.5
ServletRequest Interface methods

Since the basic Servlet interface is not protocol-specific, servlets are likely to use
HTTP as the basis of their communication. The HttpServlet class, a class that
implements the Servlet interface is provided to give additional support methods
that are useful when handling this protocol.

The Servlet API provides two additional interfaces that can be used with the
HttpServlet class. These interfaces are HttpServletRequest and
HttpServletResponse, which extend the ServletRequest and ServletResponse
interfaces described earlier.

Handling HTTP Requests

We have written a program by extending the GenericServlet class. Because most


servlets are implemented on web services that use the HTTP protocol to interact
with clients, the most common way to develop servlets is by extending the
javax.servlet.http.HttpServlet class.
The HttpServlet class extends the GenericServlet base class and provides a
framework for handling the HTTP protocol. Because it is an abstract class, servlet
writers must subclass it and override at least one method. The methods normally
overridden are:

20
J2EE Servlets & JSP

===========================================================================================================================
• doGet, if HTTP GET requests are supported. Overriding the doGet method
automatically also provides support for the HEAD and conditional GET
operations.
• doPost, if HTTP POST requests are supported.
• doPut, if HTTP PUT requests are supported.
• doDelete, if HTTP DELETE requests are supported.
• The lifecycle methods init and destroy, if the servlet writer needs to manage
resources that are held for the lifetime of the servlet. Servlets that do not
manage resources do not need to specialize these methods.
• getServletInfo, to provide descriptive information through a service’s
administrative interfaces.

Notice that the service method is not typically overridden. The service method, as
provided, supports standard HTTP requests by dispatching them to appropriate
methods, such as the methods listed above that have the prefix “do”.

Let us write a program that extends the HttpServlet class and uses the
ServletContext interface to get an object of the ServletContext (through
getServletContext() method- refer Table 2.2) that provided information about
the environment in which the servlet is running. We will also change the MME
type in the setContentType() method to text/html (refer Table 2.4). Now the
response given by the Web server will be in HTML text, which will be interpreted
by the client browser. The method getServerInfo() (refer Table 2.5) is then
used to display information about the server. The program is as follows:

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

public class GetServlet extends HttpServlet


{
public void doGet (HttpServletRequest req, HttpServletResponse
res )
{
try{
ServletContext sc=getServletContext();
PrintStream out = new
PrintStream( res.getOutputStream());
res.setStatus ( HttpServletResponse.SC_OK);
res.setContentType( “text/html”);
out.println(“<HEAD><TITLE> SimpleServlet Output
</TITLE>
</HEAD.</BODY>”);
out.println(“<h1> SimpleServlet Output </h1>”);
out.println(“<P>This output is from GetServlet.”);
out.println (“The name and version of the server running is
“+sc.getServerInfo());
out.println (“</BODY>”);
out.close();
}catch(Exception e) { }
}
}

Write the HTML file for the above servlet similar to the one give in the last
program. Remember to use the Get request for the Method attributed of the form

21
J2EE Servlets & JSP

===========================================================================================================================
tag and the Action name should be the same as the alias name provided while
deploying the servlets in J2EE.

Compile the servlet and then deploy the servlet following the same steps as given
before. The output produced is given in Figure 2.4:

Fig. 2.4
Output of the program

Let us write another servlet that receives two parameters from the client, the
Login name and the password and responds back to the client with a thanks
message. This servlet overrides the doPost method and uses the
getParameter() (refer Table 2.3) method to get the value of the parameter.

import java.io*;
import javax.servlet.*;
import javax.servlet.http. *;
import java.util.*;
public class Servlet2 extends HttpServlet {
public void doPost (HttpServletRequest req, HttpServletResponse
res)throws ServletException, IO Exception
{
// first, set the “content type” header of the response
res.setContentType (“text/html”);
//Get the response’s PrintWriter to return text to the client.
PrintWriter toClient = res.getWriter();
//Open the file for writing the survey results.
String LoginName = req.getParameter (“Login”);
String pwd = req.getParameter (“pwd”);
// Respond to client with a thank you
toClient.println(“<html>”);
toClient.println(“<title>Thank you!</title>”)
toClient.println(“Thank you for registering <br>”);
toClient.println(“Your Login name is “ + LoginName );
toClient.println(“</html>”);
// Close the writer; the response is done.
toClient.close ();
}
}

22
J2EE Servlets & JSP

===========================================================================================================================
The HTML for the above servlet is given below:

<html>
<head><title>Login Form</title></head>

<body>
<form action="testAlias" method="POST">
<BR><BR>
Login
<input type=text name=Login >
</BR><BR>
Password
<input type=password name=pwd>
<BR></BR>
<input type=submit value = Login>
<input type=reset value=Cancel>
</form>
</body>
</html>

Deploy the servlet and the HTML file using the J2EE server. Remember to give the
Alias name as test1Alias as given in the HTML file here. Open the Web browser
and type the URL. The HTML page as given in Figure 2.5 will be displayed.

Fig. 2.5
The Login form

After you give the Login name and the password, click on the Login button. The
following output will be displayed on the screen.

23
J2EE Servlets & JSP

===========================================================================================================================

Fig 2.6
Response from the servlet

Chapter: 3

SESSIONS IN SERVLET

Topics Discussed

 Session Management
 Session Tracking
 Cookies

3.1 Session Management

Data needs to be managed in case of multiple HTTP requests. As you know that
unlike TCP, http is a stateless protocol. This means that HTTP does not maintain a
connection to the server for the duration of a session. A session consists of
requests that are made during a single browser invocation. In other words, a
session starts when you open a browser and ends when you close it. For
example, in case of a shopping system, the list of items that are in a customers
cart should be maintained. In order to do this, the server should be able to
distinguish clients from one another and also provide a way to store data for each
individual client.

The Servlet API provides a powerful model for keeping track of session
information. For tracking sessions, you need to identify each client session
uniquely. This can be done by assigning an identifier to each client, storing that
identifier with the client and then making the client provide that identifier with
each HTTP request to the server.

3.2 Session Tracking

24
J2EE Servlets & JSP

===========================================================================================================================
Session tracking is a mechanism that services use to maintains state about a
series of requests from the same user (i.e. requests originating from the same
browser) across some period of time.

To use session tracking,

• Get a session (an HttpSession object) for a user.


• Store or get data from the HttpSession object.
• Invalidate the session (optional).

Obtaining a Session  The getSession method of the HttpServletRequest object


returns a user’s session. When you call the method with it’s create argument as
true, the implementation creates a session if necessary.

To properly maintain the session, you must call getSession before any output is
written to the responses. (If you respond using a Writer, then you must call
getSession before accessing the Writer, not just before sending any response
data.)

Storing and Getting Data from a Session The HttpSession interface provides
methods that store and return:

• Standard session properties, such as a session identifier


• Application data, which is stored as a name-value pair, where the name is a
String and the value is an object in the Java programming language. (This is
like java.util.Dictionary.)

Invalidating the Session  Invalidating a session means to remove the


HttpSession object and its values from the system. A user’s session can be
invalidated manually or, depending on where the servlet is running,
automatically. Some web servers automatically invalidate a session when there
has been no page request for some period of time. To manually invalidate a
session, use the session’s invalidate() method.

Let us now write a program that illustrates session tracking. This program keeps
track of the number of times a web page has been visited.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class counter10 extends HttpServlet
{
public void service (HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw = res.getWriter();
HttpSession hs = req.getSession(true);
if (hs.getAttribute ("counter")==null)
{
hs.setAttribute("counter", new Integer (1));
}
else
{
int count= ((Integer) hs.getAttribute ("counter")) .intValue()+1
hs.setAttribute ("counter", new Integer(count));

25
J2EE Servlets & JSP

===========================================================================================================================
}
pw.println ("<h1>you have visited the
page"+hs.getAttribute ("counter") +
" no of times</h1>");
}
}

The HTML for the above program is as follows:

<body>
<form method = get action =”testAlias”>
<input type=submit>
</form>
</body>

After you deploy and run the servlet in a Web browser, you will get the output as
given in Figure 3.1.

Fig. 3.1
Output of Session Tracking Example

3.3 Cookies

Till now we have seen how to track session using the Servlet API, but we still
have not discussed how a unique session id is maintained between a client and
the server. This can be done using cookies. A cookie is a piece of data that can be
embedded in HTTP request or response. The server embeds a cookie value in a
response header and the browser returns this cookie value with each request.

A cookie can store information like the session ID to bind a particular HTTP
request to a session. It can contain properties like comment, version number, and
maximum lifetime. A server can provide one or more cookies to a client. Client
software, such as a web browser, is expected to support twenty cookies per host,
of at least four kilobytes each. Cookies that a client stores for a server are
returned by the client to that sever and only that server.

To write a Cookie, the following steps are taken:

To send a cookie  To send a cookie, you need to

26
J2EE Servlets & JSP

===========================================================================================================================

1. instantiate the Cookie object


2. set its attributes
3. send the cookie.

To get information from a cookie  To do this, you need to:

1. retrieve all cookies from the user’s request


2. find the cookie or cookies with the name that you are interested in, using
standard programming techniques
3. get the values of the cookies that you found.

Let us discuss each of these steps in detail:

• Instantiate the Cookie object

The javax.servlet.http.cookie is used to create a cookie object. The constructor


of this class takes two parameters, one for the name and the other for the value.
this creates a cookie with the initial name and value. You can change the value
inside the cookie later in the program by using the setValue() method.

The name of the cookie must be an HTTP/1.1 token. Tokens are strings that
contain none of the special characters. (Alphanumeric strings qualify as tokens.)
In addition, names that start with the dollar-sign character (“$”) are reserved and
cannot be used. The value of the cookie can be any string, though null values are
not guaranteed to work the same way on all browsers.

• Set Attributes of the Cookie

There are various methods that can be used to set various cookie values and
attributes. Table 3.1 lists some such methods.
Method Description
setComment(String) If a user agent (web browser) presents
this cookie to a user, the cookie’s
purpose will be described using this
comment.
setDomain(String) This cookie should be presented only to
hosts satisfying his domain name
pattern.
setMaxAge(int) Sets the maximum age of the cookie.
setPath(String) This cookie should be presented only
with requests beginning with this URL.
setSecure(boolean0 Indicates to the user agent that the
cookie should only be sent using a
secure protocol (https).
setValue(String) Sets the value of the cookie should only
be sent using a secure protocol (https).
setVersion(int) Sets the version of the cookie protocol
used when this cookie saves itself.

Table 3.1
Methods to set cookie values and attributes.

• Sending Cookies

27
J2EE Servlets & JSP

===========================================================================================================================
Cookies are sent as headers of the response to the client; they are added with
the addCookie method of the HttpServletResponse class. If you are using a Writer
to return text data to the client, you must call the addCookie() method before
calling the HttpServletResponse’s getWriter method.

• Retrieving the Cookies

Clients return cookies as fields added to HTTP request headers. To retrieve any
cookie, you must retrieve all the cookies using the getCookies() method of the
HttpServletRequest class.

The getCookies() method returns an array of Cookie objects, which you can
search to find the cookie or cookies that you want. Since multiple cookies can
have the same name, name of a particular cookie can be obtained by using the
getName() method.

• Getting the value of a cookie

Values of a cookie can be obtained by using the getValue() method.

Let us now write a program that adds three cookies and sets their maximum age
using the setMaxAge() method (refer Table 3.1) and displays a message on the
Web browser.

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

public class cookie1 extends HttpServlet


{
public void service (HttpServletRequest req,HttpServletResponse
res) throws ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter p = res.getWriter ();
Cookie c = new Cookie ("EmpNo", "8000");
Cookie c1 = new Cookie ("Emp_Name", "Ganesh");
Cookie c2 = new Cookie ("User-id", "Ganesh_in");
c.setMaxAge (10000);
c1.setMaxAge (10000);
c2.setMaxAge (10000);
res.addCookie (c);
res.addCookie (c1);
res.addCookie (c2);
p.print ("<html><body>");
p.print ("<body> Response sets 3 cookies</body><br>");
p.print("<h1> Thank U </h1>");
}
}

The HTML file is given below:

<body>
<form method = get action = “soma”>

28
J2EE Servlets & JSP

===========================================================================================================================
<input type=”submit”>
</form>
</body>

Deploy this application on J2EE and run it in Web Browser. The following will be
displayed in the Web Browser.

Fig. 3.2
Output of the Cookie Program

The cookies are saved on your machine. You can have a look at the folder named
cookies on your machine and open the file with the name you specified for the
context root (while deploying). The file is given in Figure 7.26. As you can see
from the Figure 7.26, three cookies have been added. You can retrieve the
cookies using the getCookies () method as discussed earlier.

29
J2EE Servlets & JSP

===========================================================================================================================

Chapter: 4

IMPLEMENTING INTERSERVLET COMMUNICATION

Topics Discussed

 Servlet Collaboration
 Servlet Chaining
 Request Dispatching

4.1 Servlet Collaboration

In the default servlet model, a servlet receives an HTTP request, executes some
application logic, and prepares the response. This completes one request-
response trip for the client. However, there are several scenarios in which this
basic model is not adequate:

 Several receive an HTTP request from a client, processes application logic,


and a JavaServer Page drives the response. In this case the servlet is not
responsible for response generation. Instead, the JSP page is responsible
for dynamic content.

 A servlet receives an HTTP request from a client, and processes application


logic partially, and then hands over the request to another servlet. The
second servlet completes the application logic, and either prepares the
response, or requests a JSP page to drive the response.

In both the scenarios, the servlets is not completely responsible for processing a
request. Instead, it delegates the processing to another servlet (or a JSP page,
which is equivalent to a servlet at run-time).

There are two types of solutions for addressing the above requirements:

 Servlet chaining: This was once a very widely used approach, and
supported by some of the servlet engine vendors. Although this is not
supported by the Java Servlet API specification, for the sake of
completeness, you’ll find a short description below.

 Request Dispatching: Request dispatching allows one servlet to dispatch


the request to another resource (a servlet, a JSP page, or any other
resource). Prior to version 2.2 of the servlet API, this approach used to be
called `inter-servlet communication’. The API for supporting inter-servlet
communication has now been deprecated, and has been replaced by
request dispatchers.

30
J2EE Servlets & JSP

===========================================================================================================================

4.2 Servlet Chaining

Servlet chaining predates J2EE, and its component model. The idea of servlet
chaining is very simple: you design a set of servlets, each of which does a single
task. After developing these servlets, you configure your servlet engine to specify
a chain of servlets for a given URL path alias. Once the servlet engine receives a
request for this alias, the servlet engine invokes the servlets in the specified
order. This is similar to piping on Unix, where output of one program becomes
input for another program in the pipe.

Suppose you’ve servlets A, B, and C executing three parts of a request-response


process for a single customer service. Let’s assume that / custService is the alias
given to this chain (/custService=A, B, C). Consider a browser sending a request
to the URL path pointing to this alias. The servlet engine sends all requests for
this alias to servlet A. After executing sever A’s service method, the servlet
engine invokes servlet B’s service method, followed by C’s service method. The
final response is then sent to the client. Briefly, this is servlet chaining. Refer to
the figure below for an overview of this approach:

Servlet Engine

Alias Servlet A

Client Servlet B
(Browsers)

Servlet C

The key feature of servlet chaining is that you configure the servlet engine to do
the chaining. During setup, you specify the order in which these servlets should
be invoked.

Servlet chaining was initially introduced in the Java Web Server, but was never
part of the servlet APT specification. You’ll still find some books talking about
servlet chaining, but be advised that this non-standard feature is not supported
by most of the Web containers today. Instead, you should consider using the
request dispatching approach.

4.2 Request Dispatching

31
J2EE Servlets & JSP

===========================================================================================================================
Request dispatching allows a servlet or a JSP page to dispatch a request to
another servlet, (or a JSP page, or even a plain HTML page), which will then be
responsible for any further processing and for generating the response.

When the web container receives a request, it constructs request and response
objects and invokes one of the servlet’s service methods with the request and
response objects. This is a process of the web container dispatching a request to
a servlet. What if this servlet wants to dispatch the same request to another
servlet after some preliminary processing? For this purpose, the first servlet
should be able to obtain a reference to the second servlet. Using this reference,
the first servlet can dispatch a request to the second servlet. In simple terms,
this is request dispatching.

The Java Servlet API has a special interface called


javax.servlet.RequestDispatcher for this purpose.

• RequestDispatcher Interface

public Interface RequestDispatcher

This interface encapsulates a reference to another web resource at a specified


path within the scope of the same servlet context. A
javax.servlet.RequestDispatcher object can be used to dispatch requests to other
servlets and JSP pages.

This interface has two methods, which allow you to delegate the request-
response processing to another resource, after the calling servlet has finished any
preliminary processing.

• The forward() Method

public void forward(ServletRequest request, ServletResponse response) throws


ServletException, java.io.IOException

This method lets you forward the request to another servlet or a JSP page, or an
HTML file on the server; this resource then takes over responsibility for producing
the response.

• The include() Method

public void include (ServletRequest request, ServletResponse response) throws


ServletException, java.io.IOException

This method lets you include the content produced by another resource in the
calling servlet’s response.

• Obtaining a RequestDispatcher Object

There are three ways in which you can obtain a RequestDispatcher object for a
resource:

 javax.servlet.ServletContext methods get RequestDispatcher() and


getNameDispatcher():
public RequestDispatcher getRequestDispatcher(String path)
public RequestDispatcher getNameDispatcher(String name)

32
J2EE Servlets & JSP

===========================================================================================================================
 javax.servlet.ServletRequest method getRequestDispatcher():

public RequestDispatcher getRequestDispatcher(String path)

Although these methods serve the same purpose, the usage depends on what
information is available to you.

The two getRequestDispatcher() methods accept an URL.path referring to the


target resource. However, the getRequestDispatcher() method on
javax.servlet.ServletContext requires the absolute path (that is, the path name
should be begin with a/). For example, if you have a servlet
/myWebApp/servlet1, and want to get the RequestDispatcher object for
/myWebApp/servlet/servlet2, you should specify the complete path relative to the
root context. Here the root context is /myWebApp, and the absolute path is
/servlet/servlet2.

The same method on javax.servlet.ServletRequest accepts both absolute and


relative paths. In the above example, you could now also servlet2 as the path.

A javax.servlet.ServletRequest is associated with a URL path, and the web

container can use this to resolve relative paths into absolute paths.

The getNameDispatcher () method is a convenience method that accepts a name


associated with the servlet. This is the same name that you specify the
deployment descriptor in the<servlet-name> element.

Note that the target resource (except for static resources) should implement the
same type of HTTP request that the original servlet receives.

Example program for demonstrating the Servlet chaining is given below.

The HTML file with two fields name and password will be is posted to the Dispatch
Servlet. The code of the HTML file is as follow:

The HTML file

<html>
<head><title>Login Form</title></head>
</body>
<form action="testAlias" method="POST">
<BR><BR>
Login <input type=text name=name>
</BR><BR>
Password <input type=password name=pass>
<BR></BR><input type=submit value = Login>
<input type=”reset” value=Cancel>
</form>
</body>
</html>

The Dispatch Servlet will do the following or including according to the


parameters we pass through the text box in the HTML page.

The Dispatch Servlet is as follows

33
J2EE Servlets & JSP

===========================================================================================================================

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Dispatch extends HttpServlet
{
RequestDispatcher rd;
public void service (HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/plain");
PrintWriter p = res.getWriter ();
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if (name.equals("Smitha")==false)
{
rd=req.getRequestDispatcher("/forward");
rd.forward(req,res);
}
else
{
rd=req.getRequestDispatcher("/include");
rd.include(req,res);
}
p.println("The password given is "+pass);
}

The ForwardServlet.java is the Servlet to which the control is forwarded if the


condition not satisfied.

The ForwardServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ForwardServlet extends HttpServlet
{
public void service (HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/plain");
PrintWriter p = res.getWriter ();
String name=req.getParameter("name");
p.println("The username given is "+name);
p.println("So it is forwarded to the Forward Servlet");
}
}

The IncludeServlet is the Servlet which is the one when included in between when
the condition satisfied .In this servlet the name alone is extracted and printed and
the pass word will be printed in the calling servlet only.

The IncludeServlet.java

34
J2EE Servlets & JSP

===========================================================================================================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class IncludeServlet extends HttpServlet
{
public void service (HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType ("text/plain");
PrintWriter p = res.getWriter ();
String name=req.getParameter("name");
p.println("The username given got in the Include page is "+name);
p.println("Back to the called servlet");
}
}

The inputs and outputs can be verified from the following figures.

35
J2EE Servlets & JSP

===========================================================================================================================

For the above input the Include servlet is invoked in between and the output will
be as above.

For the above input the control is forwarded to the ForwardServlet and the name
is printed there in the ForwardServlet.

36
J2EE Servlets & JSP

===========================================================================================================================

Chapter: 5

JAVA SERVER PAGES

Topics Discussed

 Introducing JSP
 The Nuts and Bolts
 JSP Directives
The page Directive
The Include Directive
The taglib Directive
 Scripting Elements
Declarations
Scriplets
Expressions
 Standard Actions

The goal of the JavaServer Pages (JSP) specification is to simplify the creation
and management of dynamic web pages, by separating content and presentation.
JSPs are basically files that combine standard HTML 9or XML) and new scripting
tags. JSPs therefore look somewhat like HTML, but they get translated into Java
services the first time they are invoked by a client. The resulting servlet is a
combination of the HTML from the JSP file and embedded dynamic content
specified by the new tags. (This is not to say that JSPs must contain HTML: a JSP
page might be composed only of Java code, or of custom tags that refer to
externally compiled classes.)

In this chapter we will look at:

5.1 Introducing JSP

JSP is not a product but, like other Java APIs, a specification provided by Sun
Microsystems for vendors to implement; the JSP specification builds on the
functionality provided by the servlet specification. So what differentiates JSPs
from servlets?

 Servlets are Java’s answer to CGIs. They execute on the server and
intercept browser requests, acting as a sort of middle layer between
clients and other applications. In doing so, servlets tend to mix the
dynamic content into the static part to generate HTML.
 JSPs, on the other hand, are more in line with the J2EE model of
separating static and dynamic content – separating presentation and logic
– in a web application. That I the prime objective:

Simplifying the dynamic presentation layer in a multi-tiered


architecture.

Whereas services force you to mix the code with the static content. JSPs can use
beans with a specified scope to separate the code out, or tag extensions,
which are covered in Chapters 12 and 13.

37
J2EE Servlets & JSP

===========================================================================================================================

Keep in mind, that even though JSPs contain special scripting tags, under
the
hood they are nothing but servlets.

A simple JSP might look like this:

<%@page import=”java.util.Date”%>
<html>
<body>
The current time is <%=new Date(), toString() %>
</body>
</html>

5.2 The Nuts and Bolts

Let us jump head-on into writing JSPs, The structure of a JSP page is a cross
between a servlet and an HTML page, with Java code enclosed between the
constructs <% and %> and other XML-like tags interspersed.

JSP tags fall into three categories:

 Directives: These affect the overall structure of the servlet that results
from translation

 Scripting elements: These let you insert Java code into the JSP page (and
hence into the resulting servlet)

 Actions: These are special tags available to affect the runtime behavior of
the JSP

 You can also write your own tags, as we shall see in Chapters 12 and 13.

Some general rules are applicable to JSP pages:

 JSP tags are case-sensitive.

 Directives and scripting elements have a syntax, which is not based on


XML, but an alternative XML-based syntax is also available.

 Tags based on XML syntax have either a start tag with optional attributes,
an optional body, and a matching end tag; or they have an empty tag
(possibly with attributes – see example below):

<somejsptag attributename=”attribute value”>


body
</somejsptag>

or:

<somejsptag attributename=”attribute value” />


 Attribute values in tags always appear quoted; either single or double
quotes can be used. The special strings &apos; and &quot; can be used
(just as in HTML) if quotes are a part of the attribute value itself.

38
J2EE Servlets & JSP

===========================================================================================================================
 Any whitespace within the body text of a document is not significant,
but is preserved during translation into a servlet.

 The character \ (backlash) can be used as an escape character in a tag


(for example, to use %, the sequence \ % can be used).

 URLs used by JSPs follow servlet conventions, and a URL starting with
a /, called a context-relative path, is interpreted with reference to the
web application to which the JSP page belongs. (The ServletContext is
available as an implicit object within JSP pages, as well will see later.)

 If the URL does not start with a / it is interpreted relative to the


current JSP.

5.3 JSP Directives

JSP directives serve as message sent to the JSP container from the JSP. They are
used to set global values such as class declarations, methods to be implemented,
output content type, etc., and do not produce any output to the client. Directives
have scope for the entire JSP file; in other words, a directive affects the whole
JSP file, but only that file. Directives start with <%@ and end with %>; the
general syntax is:

<%@ directivename attribute=”value” attribute=”value” %>

There are three main directives that can be used in JSP:

 The page directive


 The include directive
 The taglib directive

5.3.1 The page Directive

The page directive is used to define and manipulate a number of important


page-dependent attributes that affect the whole JSP (the entire compiled class
file), and communicates these attributes to the JSP container. A page can contain
any number of page directives, in any order, anywhere in the JSP. They are all
assimilated during translation and applied together to the page. however, there
can be only one occurrence of any attribute/value pair defined by the page
directives in a given JSP. (An exception is the import attribute: there can be
multiple imports.)

The general syntax of the page directive is:

<%@ page ATTRIBUTES %>

where the valid attributes are name value pairs as described overleaf:

Attribute Description Default value


language Defines the scripting language to be “Java”
used. For future use if JSP containers
support multiple languages.
extends The value is a fully qualified class name Omitted by default
of the superclass that the generated)
must extend.

39
J2EE Servlets & JSP

===========================================================================================================================
This attribute should normally be
avoided, and only used with extreme
caution, because JSP engines usually
provide specialized super-classes with a
lot of functionality to be extended by the
generated servlet classes. Use of the
extends attribute restricts some of the
decisions that a JSP container can make.
import Comma separated list of packages or Omitted by default
classes, just like import statements in
usual Java code.
session Specifies whether the page participates “true”
in an HTTP session. When “true” the
implicit object named session (which
refers to the
javax.servlet.http.HttpSession) is
available and can be used to access the
current/new session for the page.

If “false”, the page does not participate


in a session and the implicit session
object is unavailable.
buffer Specifies the buffering model for the Implementation
output stream to the client. dependent; at least 8kb
If the value is “none”, then no buffering
occurs and all output is written directly
through to the ServletResponse by a
PrintWriter.

If a buffer size is specified (such as


“24kb”) then output is buffered with a
buffer size not less than that value.
autoFlush If “true”, the output buffer to the client “true”
is flushed automatically when it is full.

If “false’, a runtime exception is raised


to indicate buffer overflow.
isThreadSafe Defines the level of thread safety “true”
implemented in the page.

If the value is “true” the JSP engine may


send multiple client requests to the page
at the same time.

If “false” then the JSP processor queues


up client requests sent to the page for
processing, and processes them one at a
time, in the order they were received.
This is the same as implementing the
javax.servlet.SingleThreadModel
interface in a servlet.
info Defines an informative string that can Omitted by default
subsequently be obtained from the
page’s implementation of the
Servlet.getServletInfo() method.
errorPage Defines a URL to another JSP page, Omitted by default

40
J2EE Servlets & JSP

===========================================================================================================================
which is invoked if an unchecked
runtime exception is thrown. The page
implementation catches the instance of
the Throwable object and passes it to
the error page processing. See the
isErrorPage attribute below.
isErrorPage Indicates if the current JSP page is “false”
intended to be another JSP page’s error
page.

If “true”, then the implicit variable


exception is available and refers to the
instance of the java.lang.Throwable
thrown at run-time by the JSP causing
the error.
contentType Defines the character encoding for the The default value for
JSP and the MIME type for the response the MIMETYPE is
of the JSP page. text/html; the default
value for the CHARSET
This can have either the form is ISO-8859-1.
“MIMETYPE” or “MIMETYPE;
charset=CHARSET” with an optional
whitespace after the’;”.

CHARSET, or character encoding, if


specified, must be the OIANA value for a
character encoding.

Unrecognized attributes result in fatal translation errors.

Example

The following JSP, pageDirective.jsp, contains an attribute-rich page directive:

<%@ page language=”Java” import=”java.rmi.*, java.util.*”


session=”true” buffer=”12kb’ autoFlush=”true”
info=”my page directive jsp” errorPage=”error.jsp”
isErrorpage=”false” isThreadSafe=”false”%>
<html>
<head>
<title>Page directive test page</title>
</head>
<body>
<hl>Page directive test page</hl>

This is a JSP to test the page directive.


</body>
</html>
5.3.2 The Include Directive

The include directive instructs the container to include the content of the
resource in the current JSP, by inserting it, inline, in the JSP in place of the
directive. Of course the file specified should be accessible and available to the JSP
container.

41
J2EE Servlets & JSP

===========================================================================================================================
It is important to note that the content of the included file is parsed by the JSP
and this happens only at translation time (when the JSP page is compiled into a
servlet).

The include action is used to include resources at runtime, as we will see


later.

Most JSP containers usually keep track of the included file and recompile the JSP
if it changes (they may choose not to recompile). The server may, however,
choose whatever mechanism it prefers to read the included file. The syntax of the
include directive is:

<%@ include file=”Filename” %>

The only available attribute, file, specifies the filename of the file to include.

Example

The included file can be either a static file (such as an HTML file) or another JSP.

The example below, includeDirective.jsp, requests the inclusion, during


compilation, of a copyright file containing HTML legal disclaimers.

<html>
<head>
<title>Include directive test page 1</title>
</head>
<body>
<h1>Include directive test page 1</h1>
<%@ include file="included.html"%>
</body>
</html>

included.html contains the following:

<font color="red" size="12">


This is the content from the included HTML page
<font>

On placing both these files in the C:\ProJavaServer\Chapter8\JSPExamples


directory and requesting http://localhost:8080
/JSPExamples/includeDirective.jsp, the resulting output is as follows:

42
J2EE Servlets & JSP

===========================================================================================================================

The new example shows how a JSP can be included. Consider the file
includeDirective2. jsp:

<html>
<head>
<title>Include directive test page 1</title>
</head>
<body>
<h1>Include directive test page 1</h1>
<%@ include file="included.html"%>
</body>
</html>

The included JSP included.jsp is:

<%@ page import=”java.util.Date” %>


Current date is <%= new Date() %>

Again, save both these files to the C:\ProJavaServer\Chapter8\JSPExamples


directory. The result on requesting
http://localhost:800/JSPExamples/includeDirective2.jsp is:

When includedirective2.jsp is translated, the relevant portion of the resulting


servlet code, striped of comments, looks like this:

out.write(“<html>\r\n <head.\r\n <title>Include directive test page


2</title>\r\n </head>\r\n <body>\r\n <h1>Include directive test
page
2</h1>\r\n\r\n “);
out.write(‘\r\n”);
out.print (“Current date is “ );
out.print (“ + new Date());
out.write (“\r\n);
out.write (“\r\n </body<\r\n</html>\r\n”);

43
J2EE Servlets & JSP

===========================================================================================================================
You can see that the code from the included file has been inlined into the
translated servlet.

5.3.3 The taglib Directive

The taglib directive allows the page to use tag extensions (customs tags) –
see Chapters 12 and 13. It names the tag library that contains compiled Java
code defining the tags to be used. The engine uses this tag library to find out
what to do when it comes across the custom tags in the JSP. The syntax of the
taglib directive is:

<%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>

and the available attributes are:

Attribute Description Default value


uri A URI (Uniform Resource Identifier) that Not specifying a value
identified the tag library descriptor. A tag causes a compilation
library descriptor is used to uniquely error
name the set of custom tags and tells the
container what to do with the specified
tags.
tagPrefix Defines the prefix string in Not specifying a value
prefix:tagname that is used to define the causes a compilation
custom tag. error.

The prefixes jsp, jspx, java, javax,


servlet, sun, and sunw are reserved.

For example if this value is mytag then


when the container comes across any
element that starts like <mytag:tagname
… /> in the JSP, it references the tag
library descriptor specified in the URI.

Tag libraries are a very powerful, and often misunderstood, concept, and
will be covered in detail in coming Chapters.

5.4 Scripting Elements

JSP scripting elements allow java code – variable or method declarations,


scriptlets (arbitrary Java code), and expressions – to be inserted into your JSP
page.

5.4.1 Declarations

A declaration is a block of Java code in a JSP that is used to define class-wide


variables and methods in the generated servlet. Declarations are initialized when
the JSP page is initialized, and have `class’ scope in the generated servlet, so
that anything defined in a declaration is available throughout the JSP to other

44
J2EE Servlets & JSP

===========================================================================================================================
declaration, expressions, and code. A declaration block is enclosed between <% !
and %> and does not write anything to the output stream. The syntax is:

<%! Java variable and method declaration(s) %>

Example

Consider the simple JSP below, declaration.jsp:

<%!
int numTimes = 3;

public String sayHello(String name) {


return "Hello, " + name + " ! " ;
}
%>

<html>
<head>
<title>Declaration test page </title>
</head>
<body>
<h1>Declaration test page</h1>

<p>The value of numTimes is <%= numTimes %>.</p>


<p>Saying hello to reader: " <%= sayHello("reader") %>". </p>
</body>
</html>

This declares an int variable called numTimes, and a sayHello () method that
greets the requested person. Further down the page, expression elements (to be
shortly) are used to return the value of numTimes to the browser and to invoke
the sayHello () method.

When declaration.jsp is saved to the C:\ProJavaServer\Chapte8\JSPExamples


directory and http: // localhost; 8080/JSPExamples/declaration. jsp is requested,
the output is as follows:

The generated servlet contains the declarations code:

import javax.servlet.*;
// … more import statements

45
J2EE Servlets & JSP

===========================================================================================================================
public class 0002fdeclaration0002ejspdeclaration_jsp_1
extends HttpJspBase (

int numTimes = 3;

public String sayHello (String name) (


return “Hello, “ + name + “ !” ;
}

// More generated code.

5.4.2 Scriptlets

A scriptlet is a book of Java code that is executed during the request-processing


time, and is enclosed between <% and %> tags. What the scriptlet actually does
depends on the code itself, and can include producing output for the client.
Multiple scriptlets are combined in the generated servlet class in the order they
appearing the JSP. Scriptlets, like any other Java code block or method, can
modify objects inside them as a result of method invocations.

In Tomcat, all the code appearing between the <% and %> tags in the JSP gets
put into the services() method of the servlet, as is, in the order in which it
appeared. It is therefore processed for every request that the servlet receives.
The syntax for scriplets is:

<% Valid Java code statements %>

Example

In scriplet.jsp below, a scriptlet executes a loop 10 times, printing out a message


each time to the browser window (using the implicit object out) and to the
System.out stream (in other words, to the console window within which Tomcat is
running).

<html>
<head>
<title>Scriptlet test page</title>
</head>
<body>
<h1>Scriptlet test page</h1>

<%
for(int i=0;i< 10; i++) {
out.println ("<b>Hello World. This is a scriptlet test " + i
+"</b><br>");
System.out.println ("This goes to the System.out stream " +
i);
}
%>
</body>
</html>

Save scriplet.jsp to the C:\ProJavaServer\Chapter1\JSPEampales\directory and


request http://localhost:8080/JSPExamples/scriptlet.jsp. The output to the
browser window should be:

46
J2EE Servlets & JSP

===========================================================================================================================

5.4.3 Expressions

An expression is a shorthand notation for a scriptlet that sends the value of a


Java expression back to the client. The expression is evaluated at HTTP request
processing time, and the result is converted to a String and displayed.

An expression is enclosed in the <%=and%> tags. If the result of the expression


is an object, the conversion is done by using the object’s toString() method. The
syntax is:

<%= Java expression to be evaluated %>

Example

Consider the example JSP overleaf (expression.jsp – again, save it in


C:\ProJavaServer\Chapter8|JSPExamples), which sets up a simple counter and
shows declarations, scriptlets, and expressions working together:

<html>
<head>
<title>Expression test page</title>
</head>
<body>
<h1>Expression test page</h1>
<%! int i=0 ; %>
<%
i++;
%>
Hello World!
<%= "This JSP has been accessed " + i + " times" %>
</body>
</html>

47
J2EE Servlets & JSP

===========================================================================================================================
An int variable is declared, and initially has the value 0. Each time this instance
of the generated servlet is called (when the browser requests
http://localhost:8080\JSPEamples\expression. jsp) the variable is incremented by
the scriptlet. Finally, an expression is used to printout the value of I, together
with some surrounding text.

After this JSP has been requested a number of times, the browser will display.

5.5 Standard Actions

Standard actions are tags that affect the runtime behavior of the JSP and the
response sent back to the client. They have to be provided by all containers,
irrespective of the implementation.

Effectively, a standard action is a tag that can be embedded in a JSP page.


During compilation into a servlet, the container comes across this tag and
replaces it with Java code the corresponds to the required predefined task.

For example when it comes across the standard include action.

<jsp:include page=”myjsp.jsp” flush=”true” />

it takes the JSP myjsp. jsp, compiles it (if necessary), and includes the output
produced by myjsp.jsp in the response, in place of the action tag. We will
examine the semantics of this action in detail in a while.

The standard actions serve to provide page authors with basic functionality to
exploit for common tasks. The standard action types are:

 <jsp:useBean>

 <jsp:setProperty>

 <jsp:getProperty>

 <jsp:param>

 <jsp:include>

 <jsp:forward>

 <jsp:plugin>

48
J2EE Servlets & JSP

===========================================================================================================================

5.5.1 jsp:useBean

To separate code from presentation, it would be a good idea to encapsulate the


code in a Java object (a JavaBean), and then instantiate and use this object
within our JSP. The <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty>
tags assist with this task.

The <jsp:useBean> action is used to instantiate a JavaBean, or locates an


existing bean instance, and assigns it to a variable name (or id). We can also
specify the lifetime of the object by giving it a specific scope (we cover this later
in detail). </jsp:useBean> ensures that the object is available, with the specified
id, in the appropriate scope as specified in the tag. The object can be referenced
using as associated id from within the JSP, or even from other JSPs, depending
on the scope.

The syntax for the <jsp:useBean> action is:

<jsp:useBean id=”name” scope=”scopeName” beandetails />

where and beandetails is one of:

 class=”className”

 class=”className” type=”typeName”

 beanName=”beanName” type=”typeName”

 type=”typeName”

The attributes available are:

Attribute Description Default values


id The case sensitive name used to identify the No default
object instance. value
scope The scope within which the reference is available. “page”
Possible values are “page”, “request”, “session”,
and ‘application”. These values will be explained
shortly.
class The fully qualified class name. No default
value
beanName The name of a bean, as you would supply to the No default
instantiate() method in the java.beans.Beans value
class. This attribute can also be a request time
expression.

It is permissible to supply a type and a


beanName, and omit the class attribute.

The beanName follows the standard bean


specification and can be of the form “a.b.c.’,
where “a.b.c.” is either a class, or the name of a
serialized resource in which case it is resolved as
‘a/b/c.er”. 9See the javaBeans specification for
more details.)s

49
J2EE Servlets & JSP

===========================================================================================================================
type This optional attribute specifies the type of the The value of
scripting variable to be created, and follows the class
standard java casting rules. The type attribute
implemented by it, or the bean’s class itself.

Just like any casing operation, if the object is not


of this type then java.lang.ClassCastException can
be thrown at request time.

Let us examine the underlying semantics that occur because of this tag in the
order they occur:

 The container tries to locate an object that has this id, in the specified
scope.

 If the object is found, and a type has been specified in the tag, the
container tries to cast the found object to the specified type. A
ClassCastException is thrown if the cast fails.

 If the object is not found in the specified scope, and no class or beanName
is specified in the tag, an InstantiationException is thrown.

 If the object is not found in the specified scope, and the class can be
instantiated, then this is done, and a reference to the object is associated
with the given id, in the specified scope. If this fails then an
InstantiationException is thrown.

 If the object is not found in the specified scope and a beanName is


specified, then the instantiate(1) method of java.beans.Beans is invoked,
with the beanname as an argument. If this method succeeds, the new
object reference is associated with the given id, in the specified scope.

 If a new bean instance has been instantiated and the <jsp:useBean>


element has a non-empty body, the body is processed; during this
processing the new variable is initialized and available. Scriptlets or the
<jsp:setProperty> standard action can be used to initialize the ban
instance, if necessary.

The meanings of the possible values of the scope attribute will be covered in
more detail shortly, but in brief:

 Page scope means that the object is associated with this particular request
to this page.

 request scope means that the object is associated it this particular client
request. If the request is forwarded to another JSP using the
<jsp:forward> action, or if another JSP is included using the
<jsp:include> action, the object will available.

 session scope means that the object will be available during any requests
made by the name client within the current session.

 application scope means that the object will be available in any JSP page
with the same web application.

50
J2EE Servlets & JSP

===========================================================================================================================

The container looks for the Java class you specified in the CLASSPATH for that
web application. If you are creating a bean of a class you have written yourself,
place the compiled .class file either under the WEB-INF\classes directory in your
web application, or in a JAR file in the WEB-INF\lib directory.

We will see an example of the <jsp:useBean>action once we have looked at


<jsp:setProperty> and <jsp:getProperty>.

5.5.2 jsp:setProperty

The <jsp:setProperty> standard tag is used in conjunction with the


<jsp:useBean> action described in the proceeding section, to set the value of
bean properties. Bean properties can be either simple or indexed.

The properties in a bean can be set either:

 At request time from parameters in the request object

 At request time from an evaluated expression

 From a specified string (or hard coded in the page)

When setting bean properties from the request object, the JSP can choose to set
all properties in the bean via the standard action:

<jsp:setProperty name=”help” property=***/>

or a single property can be set explicitly by an action such as;

<jsp:setProperty name=”help” property=”word” />

The <jsp:setProperty> action uses bean introspection to discover what properties


are present, their names, whether they are simple or indexed, their type, and
their accessor and mutator methods.

The syntax of the <jsp:setProperty> action is:

<jsp:setProperty name=”beanName” propertydetails />

when propertydetails is one of:

 property=”*”

 property=”propertyName”

 property=”propertyName” param=”parameterName”

 property=”propertyName” value=”propertyValue”

and propertyValue is a string or a scriptlet. The attributes are:

51
J2EE Servlets & JSP

===========================================================================================================================

Attribute Description
name The name of a bean instance, which must already have been defined
by a <jsp:useBean> tag.Note that the name is <jsp.setProperty>
and the one for <jsp:useBean> must be the same.
property The name of the bean property whose value is being set.

If the property attribute has the value “ * “, the tag looks through all
the parameters in the request object and tries to match the request
parameter names and types to property names and types in the
bean. The values in the request are assigned to each matching bean
property, unless a request parameter has the value “”, in which case
the bean property is left unaltered.
param When setting bean properties from request parameters, it is not
necessary for the bean have the same property names as the request
parameters.

This attribute is used to specify the name of the request parameter


whose value you want to assign to a bean property. If the param
value is not specified, it is assumed that the request parameter and
the bean property have the same name.

If there is no request parameter with this name, or if it has the value


“ “, the action has no effect on the bean.
value The value to assign to the bean property. This can be a request-time
attribute, or it can accept an expression as its value.

(A tag cannot have both param and value attributes.)

When properties are assigned from String constants or request parameter values,
conversion is applied using the standard Java conversion methods; for example, if
a bean property is of type double or Double the java.lang.Double.valueOf (String)
method is used. However, request-time expressions can be assigned to properties
of any type, and the container performs no conversion. For indexed properties,
the value must be an array.

5.5.3 jsp:getProperty

The <jsp:getProperty> action is complementary to the <jsp:setProperty> action,


and is used to access the properties of a bean. It accesses the value of a
property, converts it to a String, and prints to the output stream to the client.

To convert the property to a String, the action:

 Invokes the toString () method on the property, if it is an object.

 Converts the value directly to a String, if it is a primitive, using the


valueOf() method of the corresponding wrapper class for the primitive
type

This is just like the behavior of Java’s System.out.println() method.

52
J2EE Servlets & JSP

===========================================================================================================================
The syntax is:

<jsp:getProperty name=”name” property=”propertyName” />

and the available attributes are:

Attribute Description
name The name of the bean instance from which the property is obtained.
property Names the property to get; this is the instance variable in the bean.
Of course, you must create a bean before using <jsp:getProperty>,
by using <jsp:useBean> or by instantiating the object by a new
operator.

Having seen the <jsp:useBean>, <jsp:setProperty>, and<jsp:getProperty>


actions, let’s build a simple example using all three. Our example will ask the
user for their name and their favorite programming language, and then issue a
verdict on their choice. The HTML form page, beans.html, is very simple:

<html>
<head>
<title>useBean action test page</title>
</head>
<body>
<h1>useBean action test page</h1>
<form method="post" action="beans1.jsp">
<p>Please enter your username;
<input type="text" name="name">
<br>What is your favorite programming language?
<select name="language">
<option value="Java">Java
<option value="C++">C++
<option value="Perl">Perl
</select>
</p>
<p><input type="submit" value="Submit information">
</form>

</body>
</html>

This sends a POST request to beans.jsp two parameters: name and


language.beans1.jsp is also quite simple.

<jsp:useBean id="languageBean" scope="page" class="bean1.LanguageBean">


<jsp:setProperty name="languageBean" property="*" />

</jsp:useBean>
<html>
<head>
<title>useBean action test result</title>
</head>
<p>Hello, <jsp:getProperty name="languageBean"
property="name"/>.</p>
<p>Your favorite language is
<jsp:getProperty name="languageBean" property="language" />.
</body>

53
J2EE Servlets & JSP

===========================================================================================================================
</html>

All the Java code has been removed to the LanguageBean class. beans .jsp
creates an instance of LanguageBean with page scope, and uses the property-
=”*” form of the <jsp:setProperty> action to set the bean’s name and language
properties. It can then use the <jsp:getProperty> action to retrieve the values of
these properties, and also the languageComments property.

Finally, the source of LanguageBean is as follows:

package bean1;
public class LanguageBean
{
private String name;
private String language;
private String languageComments;

public LanguageBean(){}

public void setName (String name)


{
this.name = name;
}

public String getName()


{
return name;
}

public void setLanguage (String language)


{
this.language = language;
}
public String getLanguage()
{
return language;
}

This is a nice, simple class with a no-argument constructor, set and get methods
for the name and language properties, and also a getLanguageComments ()
method. This last method uses the value of the language property to issue some
comments on the user’s chosen language – this is invoked by the
<jsp:getProperty name=”languageBean” property=”languageComments”/>
action in beans.jsp.

Save beans.jsp and beans .jsp to C:\ProJavaServer\Chapter8\JSPExamples, and


languageBean.java to C:\ProJavaServer\Chapter8\JSPExamples\src. Compile the
bean into C:\ProJavaServer\Chapte8\JSPExamples\WEB-INF\classes (create this
directory first) by running the command:

javac -d ..\WEB-INF\classes LanguageBean.java

from the src directory. Then point your browser at


http: // localhost: 8080/JSPExamples/beans.html:

54
J2EE Servlets & JSP

===========================================================================================================================

Enter your name and choose your favored language, then click the Submit
information button:

The advantage of this approach over that used in previous examples (in
which we freely mixed Java code and HTML) should be clear. Removing
the logic to the languageBean class has made our JSP page much more
readable, and more easily edited by someone who is a skilled web
designer but does not understand the details of Java programming.

5.5.4 jsp:param

The <jsp:param> action is used to provide other tags with additional information
in the form of name-value pairs. It is used in conjunction with the
<jsp:include>.,<jsp:forward>, and <jsp:plugin> action, and its use is described
in the relevant sections that follow. The syntax is:

<jsp:param name=”paramname” value=”paramvalue” />

and the available attributes are:

55
J2EE Servlets & JSP

===========================================================================================================================

Attribute Description
name The key associated with the attribute. (Attributes are key-value pairs.
value The value of the attribute.

5.5.5 jsp:include

This action allows a static or dynamic resource, specified by a URL, to be included


in the current JSP at request processing time. An included page has access to
only the JspWriter object, and it cannot set headers or cookies. A request-time
exception will be thrown if this is attempted. This constraint is equivalent to that
imposed on javax.servlet.RequestDispatcher’s include () method, which is what
servlets use if they want to do this type of inclusion.

If the page output is buffered then the buffer is flushed prior to the inclusion. The
include action pays a small penalty in efficiency, and precludes the included page
from containing general JSP code.

The syntax of the <jsp:include> action is:

<jsp:include page=”URL” flush=”true” />

or:

<jsp:include page=“URL” flush=“true”>


<jsp:param name=“paramname” value=“paramvalue” />

</jsp:include>

the attributes of the <jsp:include> action are:

Attribute Description
filename The resource to include. The URL format is the same is described
earlier for the include directive.
flush In JSP 1.1 this value must always be “true”, and “false” is not
supported. If the value is “true”, the buffer in the output stream is
flushed before the inclusion is performed.

A <jsp:include> action may have one or more <jsp:param> tags in its body,
providing additional name-value pairs. The included page can access the original
request object, which will contain both the original parameters, and the new
parameters specified using the <jsp:param> tag. If the parameter names are the
same, the old values are kept intact, but the new values take precedence over
the existing values.

For example, if the request has a parameter paraml=myvalue1, and a parameter


param1-myvalue2 is specified in the <jsp:param> tag, the request received on
the second JAP will have param=myvalue2, myvalue1. The augmented attributes
can be extracted from the request using the getParameter (String paramname)
method in the javax.servlet.ServletRequest interface.

It is important to understand the difference between the include directive and this
include action; the difference is summarized in the table below:

Include Syntax Done when Included Parsing

56
J2EE Servlets & JSP

===========================================================================================================================
type content
directive <%@ include Compilation Static Parsed by
file=”filename” time container
%>
action <jsp:include Request Static or Not parsed
page=” processing Dynamic but included
filename” /> time in place

The include directive lets you include resources into multiple pages but requires
you to update the modification date on the pages doing the include if the
resource changes (in other words the container has to translate them again to
reflect the changes). The include action includes files at request-processing time.

Use the include directive if your resource is not going to change


frequently.
Use the include action when the resource is frequently changing or is
dynamic.

Let’s look at an example. The JSP below, includeAction.jsp, shows both the
include types, for both a static and a dynamic resource:

<html>
<head>
<title>Include Action test page</title>
</head>
<body>
<h1>Include Action test page</h1>

<h2>Using the include directives</h2>

<%@ include file="include2.html" %>


<%@ include file="include2.jsp" %>

<h2>Using the include action</h2>

<jsp:include page="include2.html" flush="true" />


<jsp:include page= "include2.jsp" flush="true" />
</body>
</html>

The two included files are include2.html:

<p>This is some static text in the html file</p>

and include2.jsp:

<%@ page import="java.util.Date" %>


<%= "Current date is " + new Date() %>

Saving these files in C;\PreoJavaServer\Chapter8\JSPExamples and requesting


http://locahost:8080/JSPExamples/includeAction.jsp, we get:

57
J2EE Servlets & JSP

===========================================================================================================================

Even though the output from the two types of includes may look identical, there
is a subtle difference. Let us look at an excerpt from the generated servlet class,
tidied up a little.

// …

public void _jspService (HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException {
// …

out.write (“<html>\r\n <head.\r\n <title>Include Action test


page</title>\r\n <head>\r\n <body>\r\n <h1>Include Action test
page</h1>\r\n\r\n <h2>Using the include directives</h2>\r\n\r\n “);
out.write (“<h3>This is some static text in the html file</h3>”);
out.write (“\r\n “);
out.write (“r\n”);
out.print ( “Current date is “ + new Date() );
out.write (“\r\n\r\n <h2>Using the include action</h2>\r\n\r\n
“);
{
String _jspxqStr = “ “;
out.flush();
pageContext.include (“include2.html” + _jspx_qStr);
}
out.write (“\r\n “);
{
String _jsqpx_qStr = “ “;
out.flush() ;
pageContext.include (“include2.html” + _jspx_qStr);
}
out.write (“\r\n\r\n </body>\r\n<html>\r\n);

//…
}

The highlighted lines in the above code show how the container in-lines the
resources for the include directive, and invokes them dynamically for the include
action. To reiterate the difference, see what happens when the included resources
are changed (without changing the parent JSP that includes them). Change
include2.html so that it contains:

58
J2EE Servlets & JSP

===========================================================================================================================
<p>This is some new text in the html file</p>

and change icnlude2.jsp so that its contents are now:

<p>This is the new JSP</p>

When the page is requested again, the output now looks like this

The parts included using the include directive are not altered, because the parent
JSP (includeAction.jsp) has not changed and hence is not recompiled; however,
the parts included using the include action are changed, because the include
action performs the inclusion afresh each time the parent JSP is requested.

5.5. 6 jsp: forward

The <jsp:forward> action allows the request to be forwarded to another JSP, to a


servlet, or to a static resource. This is particularly useful when you want to
separate the application into different views, depending on the intercepted
request. We saw this design approach with servlets in Chapter 9, and will see
more of it later in this chapter. The syntax is:

<jsp:forward page=“URL” />


<jsp:forward page=“URL”>
<jsp:param name=”paramname” value=paramvalue” />

</jsp:forward>

The resource to which the request is being forwarded must be in the same
context as the JSP dispatching the request. Execution in the current JSP stops
when it encounters a <jsp:forward> tag, the buffer is cleared, and the request is
modified (this is a server-side redirect and the response buffer is cleared when it
is processed) to assimilate any additionally specified parameters in the same way
as described for the <jsp:include> action.

If the output stream was not buffered, and some output has been written to it, a
<jsp:forward> action will throw a java.lang.IllegalStateException. The behavior of
this action is exactly the same as the forward () method of the
javax.servlet.RequestDispatcher.

59
J2EE Servlets & JSP

===========================================================================================================================
Let’s see a simple example of the <jsp:forward> action in use – a simple login
form. The login form itself, in forward.html, is straightforward, sending a POST
request to forward.jsp:

<html>
<head>
<title>Forward action test page</title>
</head>
<body>
<h1>Forward action test page</h1>

<form method="post" action="forward.jsp">


<p>Please enter your username:
<input type="text" name="username">
<br>and password:
<input type="password" name="password">
</p>

<p><input type="submit" value="Log in">


</form>

</body>

</html>

forward .jsp is the first JSP page we have seen that contains no HTML code:

<%
if ((request.getParameter ("username").equals ("Richard")) &&
(request.getParameter ("password").equals ("xyzzy"))) {
%>

<jsp:forward page="forward2.jsp" />

<% } else { %>

<%@ include file="forward.html" %>

<% } %>

The checks whether the username and password are acceptable to the system,
and if so forwards the request to forward2.jsp; if the login attempt fails, it uses
the include directive to present the login form to the user again.

In a real-world example the password-checking code would check against


a database or a JNDL server, the Java code would be removed to a
JavaBean or a tag extension, and the whole application would probably be
secured using HTIPS.

Finally, forward2.jsp presents the successfully logged-in user with a welcome


page. Since the original request, including the form parameters, has been
forwarded to this JSP, we can use the request object to display the user’s name:

<html>
<head>

60
J2EE Servlets & JSP

===========================================================================================================================
<title>Forward action test: Login successful!</title>
</head>
<body>
<h1>Forward action test: login successful</h1>
<p>Welcome, <%= request.getParameter("username") %>
</body>
</html>

Save all these files in C:\ProJavaServer\Chapter8|JSPExamp[les and request


http://localhost:8080/JSPExamples/forward.html:

Entering the username Richard and the password xyzzy, we get to this page:

If any other username or password is entered, the login form is displayed again.

61
J2EE Servlets & JSP

===========================================================================================================================

5.5.7 jsp:plugin

The <jsp:plugin> action is used in pages to generate client browser specific HTML
tags (<OBJECT> or <EMBED>) that result in the download of the Java Plug-in
software, if required, followed by the execution of the applet or JavaBeans
component that is specified in the tag.
The <jsp:plugin> tag can optionally have two additional support tags:

 <jsp:param>, to pass additional parameters to the Applet or JavaBeans


component.
<jsp:fallback>, to specify the content to the displayed in the client browser if the
plugin cannot be started because the generated tags are not supported. The
<jsp:fallback> tag does that the HTML ALT attribute and <NOFRAMES> tag do.

The available attributes for the <jsp:plugin> tag are:

Attribute Details Required


type Identifies the type of the component: a Yes
Bean, or an Applet
code Same as HTML syntax Yes
codebase Same as HTML syntax No
align Same as HTML syntax No
archive Same as HTML syntax No
height Same as HTML syntax No, but some browsers
do not allow an object of
zero height due to
security issues
hspace Same as HTML syntax No
jreversion The Java runtime environment version No
needed to execute this object

Default is “1.1”
name Same as HTML syntax No
vspace Same as HTML syntax No
title Same as HTML syntax No
width Same as HTML syntax No, but some browsers
do not allow an object of
zero width due to
security issues
nspluginurl URL where Java plugin can be No
downloaded for Netscape Navigator

Default is implementation defined


iepluginurl URL where Java plugin can be No
downloaded for Internet Explorer

Default is implementation defined

5.6 Implicit Objects

The Servlet API includes interfaces that provide convenient abstractions to the
developer, such as HttpServletRequest, HttpServletResponse, HttpSession, etc.
These abstractions encapsulate the object’s implementation; for example, the

62
J2EE Servlets & JSP

===========================================================================================================================
HttpServletRequest interface represents the HTTP data sent from the client along
with headers, form parameters, etc., and provides convenient methods like
getParameter(), and getHeader() that extract relevant data from the request.

JSP provides certain implicit objects, based on the servlet API. These objects are
accessed using standard variables, and are automatically available for use in your
JSP writing any extra code. The implicit objects available in a JSP page are:

 request

 response

 pageContext

 session

 application

 out

 config

 page

The request Object

The request object represents the request that triggered the service() invocation.
It is the HttpServletRequest that provides access to the incoming HTTP headers
(for example, for cookies), request type (GET/POST), and request parameters,
among other things. Strictly speaking, the object itself will be a protocol and
implementations-specific subclass of javax.servlet.ServletRequest, but few of
any), JSP containers currently support non-HTTP servlets. It has request scope.

The response Object

The response object is the HttpServletResponse instance that represents the


server’s response to the request. It is legal to set HTTP status codes and headers
in the JSP page once output has been sent to the client (even though it is not
permitted in servlets, since the output stream is buffered). Again, the object itself
will, strictly speaking, be a protocol- and implementation-specific subclass of
javax.servlet.ServletResponse. It has page scope.

The pageContext Object

The pageContext object provides a single point of access to many of the page
attribute and is a convenient place to put shared data within the page. It is of
type javax.servlet.jsp.PageContext, and has page scope.

The session Object

The session object represents the session created for the requesting client.
Sessions are created automatically, and this variable is available even when there
is no in-coming session (unless, of course, you have used a session=”false”
attribute in the page directive, in which case variable will not be available). It is
of type javax.servlet.http.HttpSession, and has session scope.

63
J2EE Servlets & JSP

===========================================================================================================================

The application Object

The application object represents the servlet context, obtained from the servlet
configuration object. It is of type javax.servlet.ServletContext and has application
scope.

The out Object

The out object is the object that writes into the output stream to the client. To
make the response object useful, this is a buffered version of the
java.io.PrintWriter class, and is of type javax.servlet.jsp.JspWriter. The buffer size
can be adjusted via the buffer attribute of the page directive.

The config Object

The config object is the ServletConfig for this JSP page, and has page scope. It is
of type javax.servlet.ServletConfig.

The page Object

The page object is the instance of the page’s implementation servlet class that is
processing the current request. It is of type java.lang.Object, and has page
scope. The page object can be thought of as a synonym to this within the page.

5.7 Scope

The scope of JSP objects – JavaBeans and implicit objects – is critical, as it


defines the how long, and from which JSPs, the object will be available. For
example, the session object has a scope, which exceeds that of a page, as it may
span several client requests and pages. The application object can provide
services to a group of JSP pages that together represent a web application.

JSP scopes internally rely on contexts. A context provides an invisible container


for resources, and an interface for them to communicate with the environment;
for example, a servlet executes in a context (an instance of ServletContext, in
fact). Everything that the servlet needs to know about its server can be extracted
from this context, and everything the server wants to communicate to the servlet
goes through the context. A rule of thumb:

Everything in JSP is associated with a context, and every context has a


scope.

What happens when a bean tag is compiled for the different values of scope can
be seen below:

Page Scope

An object with page scope is bound to the javax.servlet.jsp.PageContext.

This is relatively simple – It means that the object is placed in the PageContext
object, for as long as this page is responding to the current request. An object

64
J2EE Servlets & JSP

===========================================================================================================================
with this scope can be accessed by invoking the getAttribute() methods on the
implicit pageContext object.

The object reference is discarded upon completion of the current Servlet.service()


(in other words, when the page is fully processed by the servlets generated from
the JSP). When generating the servlet, the servlet engine creates an object in the
service() method which follows the usual object scope conversion in java. This
object is created and destroyed for each client request to the page.

This is the default scope for objects used with the <jsp:useBean> action.

Request Scope

request scope means that the object is bound to the


javax.servlet.ServletRequest, and can be accessed by invoking the getAttribute()
methods on the implicit request object.

The object reference is available as long as the HttpRequest object exists, even if
the request is forwarded to different pages, or if the <jsp:include> action is used.
The underlying, generated servlet relies on binding the object to the
HttpServletRequest using the setAttribute (String key, Object value) method in
the HttpServletRequest; this is transparent to the JSP author. The object is
distinct for every client request (in other words it is created afresh and destroyed
for each new request).

Session Scope

An object with session scope is bound to the javax.servlet.jsp.PageContext, and


can be accessed by invoking the getValue() methods on the implicit session
object.

In earlier implementations of the servlet API, a session always ran under a


separate session context. (Though deprecated for security reasons, an
implementation for the HttpSessionContext interface is still available on most
servers. It allows you to get a list of sessions or a particular session by its ID –
and that’s not really that secure.) These days, the only session ID you can get at
is the one that’s part of the request from the client, passed to the PageContext
and made available to the JSP.

The generated servlet relies on binding the object to the HttpSession using the
setAttribute (String key, Object value) method. This too is transparent to the JSP
author. The object is distinct for every client, and is available as long as the
client’s session is valid.

Application Scope

Application scope means that the object is bound to the


javax.servlet.ServletContext. An object with this scope can be accessed by
invoking the getAttribute.() methods on the implicit application object

This is the most persistent scope. The generated servlet relies on binding the
object to the ServletContext using the setAttribute (String key, Object value)
method in the ServletContext. This is not unique to individual clients and,
consequently, all clients access the same object as they all access the same
ServletContext.

65
J2EE Servlets & JSP

===========================================================================================================================

Chapter: 6

CUSTOM TAGS IN JSP

Topics Discussed

 Tag Extension 101


 Anatomy of a Tag Extension
 Tag Handlers
The javax.servlet.Jsp.tagext.Tag Interface
The javax.servlet.jsp.tagext.BodyTag Interface
The javax.servlet.jsp.tagext.BodyContent Class
Convenlence Classes
The javax.servlet.jsp.tagext.TagExtraInfo Class
Objects Available to Tag Handlers
The Simple Example Revisited
 Tag Library Descriptors
 Using Tag Extensions in JSP Pages
 Deploying the Packaging Tag Libraries
No Packaging
WAR

From the point of view of the JSP developer, the only significant new feature of
JSP 1.1 is support for tag extensions (often referred to as customs tags).
However, this proves to be very significant indeed.

Tag extensions look like HTML, (or rather, XML) tags embedded in a JSP page.
They have a special meaning to a JSP engine at translation time, and enable
application functionality to be invoked without the need to write Java code in JSP
scriptlets. Well-designed tag extension libraries can enable application
functionality to be invoked without the appearance of programming.

So in this chapter, we’ll look at the basis of writing your own tags and then in the
next chapter we’ll look at some more advanced examples. So in this chapter we
will cover:

 Tag extension basics

 The anatomy of a tag extension

 How do deploy a tag library

 How to write custom tag extensions

Let’s get started then with what tag extensions are all about.

66
J2EE Servlets & JSP

===========================================================================================================================

6.1 Tag Extension 101

Consider the <jsp:forward> action provided by the JSP specification. This tag
dispatches the current request to another page in the current web application. It
can be invoked with the following syntax:

<jsp:forward page=”next.jsp” />

We can also to add additional parameters to the request before forwarding with
an extend usage of <jsp:forward>, which nests one or more <jsp:param> tags
within the <jsp:forward> tag:

<jsp:forward page=”next.jsp” >


<jsp:param name=”image” value=”house.gif” />
</jsp:forward>

Tax extensions allow a vast range of new functionality to be added to the JSP
language and they can be invoked in a similarly intuitive way. For example, I
could create a tag named <wrox:forward>, specify what attributes and subtags,
if any, it requires, and implement it to perform a custom action before
forwarding. Not only can this be added simply into the web page, it enforces
separation of code and presentation, decouples the call from the class that
implements the functionality associated with the tag, and can be simply
incorporated into a design tool.

The key concepts in tag extensions are:

 Tag name:
A JSP tag is uniquely identified by a combination of prefix (in this case
jsp), and suffix (in this case forward), separated by a colon.

 Attributes:
Tags may have attributes, which use the XML syntax for attributes. The
<jsp:forward> tag above has one attribute (page), while the <jsp:param>
attribute has two (name and value). Attributes may be required or
optional.

 Nesting:
Note how the <jsp:param> subtag is used in the second example above.
Tag extensions can detect nested tags at runtime and cooperate. A tag
directly enclosing another tag is called the parent of the tag it encloses: in
the example above, the <jsp:forward> tag is the parent of the
<jsp:param> tag.

 Body content:
This is anything between the start and end elements in a JSP tag,
excluding subtags. A tag extension can access and manipulate its body
content. Neither the <jsp:forward> not <jsp:param> tags require body
content. We will see later an example of a tag that can reverse its body
content. It will be invoked like this (the body content is shown in bold):

<examples:reverse>
Able was I ere I saw Elba
</examples:reverse>

67
J2EE Servlets & JSP

===========================================================================================================================

The functionality associated with a tag is implemented by one or more


Java classes. The tag handler (the class implementing the tag itself) is a
JavaBean, with properties matching the tag’s XML attributes. A Tag
Library Descriptor (TLD) file is an XML document that describes a tag
library, which contains one or more tag extensions. The JSP taglib
directive must be used to import the tag library in each JSP that wishes
to use any of them.

Why, besides a clever syntax, might we choose to use tax extensions rather than
JSP bean? Are tag extensions not simply another way of allowing JSP pages to
parcel out work to Java classes?

Due to the richer interaction between the hosting JSP page and tax extensions,
tag extensions can achieve directly what beans can only achieve in conjunction
with scriptlets. Tag extensions may access the PageContext, write output to the
output writer, redirect the response, and define scripting variables. As an
indication of their power, all the standard JSP actions provided via tags of form
<jsp:XXX> could be implemented using tag extensions. The behavior of tag
handlers is configured by their XML attributes and their body content (which can
be the result of evaluating JSP expressions at runtime).

Typical uses of tag extensions are:

 To conceal the complexity of access to a data source or enterprise object


from the page (possibly, the page author, who may not be experienced
with enterprise data)

 To introduce new scripting variables into the page

 To filter or transform tag content, or even interpret it as another language

 To handle iteration without the need for scriptlets

Tag extensions can be used to deliver a range of functionality limited only by


developers’ imaginations and sensible programming practice.

Tax extensions differ from beans in that they are common building blocks, not
tailored resources for a particular page or group of pages. Tags receive the
attributes that control their behavior from the JSP pages using them, not the
request to a particular JSP (as in the case of request bean property mappings) A
well-designed tag extension may be used in many JSP pages.

This reusability is particularly important. Since their implementation and


interaction with the JSP engine is well defined in the JSP 1.1 specification,
libraries of tax extensions can be developed and distributed, on a commercial or
open source basis. Generic tags can be developed for particular industries or
application types.

Tag extensions, although new to JSP, are a very old concept in dynamic page
generation. Products such as Apple’s WebObjects and BroadVision have delivered
rich functionality through custom tags for years, although in a proprietary
context. This experience in the use of custom tags can be valuable to JSP
developers.

68
J2EE Servlets & JSP

===========================================================================================================================
Tag extensions are a particularly welcome addition to the JSP developer’s armory
because they are easy to implement. The API surrounding them is relatively
simple, and it is possible to use them to achieve results quickly. This is a
reflection of the elegance of the design if the tag extension mechanism; in the
true Java spirit it delivers rich functionality without excessive complexity:

The examples and most of the discussion in this chapter and the next
assume that tag extensions will be used to generate HTML markup. While
this is currently their most likely use, tag extensions can be used to
generate any content type supported by JSP:

6.2 Anatomy of a Tag Extension

Before we return to our simple example, let’s cover some basic theory of tag
extensions.

A number of components are required to implemented a tag extension. The


minimal requirement is a tag handler and a tag library descriptor.

 A tag handler is a Java bean implementing one of two interfaces defined in


the javax.servlet.jsp.tagext package, Tag or BodyTag. These interfaces
define the lifecycle events relevant to a tag; most importantly, the calls
the class implementing the tag will receive when the JSP engine
encounters the tag’s opening and closing tags.

 A tag library descriptor, as we have seen, is an XML, document containing


information about one or more tag extensions.

More complex tags will require an additional class extending the abstract class
javax.servlet.jsp.tagext.TagExtraInfo to provide information about scripting
variables that are made available to JSPs through the use of tags.

TagExtraInfo subclasses may also perform custom validation of tag attributes. Of


course, the classes implementing a tag may require any number of helper
classes, which will need to be packaged with the tag for it to be a complete
deployable unit.

Before tags can be used in a JSP, the taglib directive must be used to import a
tag library and associate the tags it contains with a prefix.

Let’s look at each of these requirements in turn.

6.3 Tag Handlers

When the JSP engine encounters a tag extension in a JSP at translation time, it
parses the tag library descriptor to find the required tag handler class, and
generates code to obtain, and interact with, the tag handler. The Tag or BodyTag
interfaces, one of which must be implemented by any tag handler, define
callbacks that the servlet resulting from the JSP engine’s code generation will
make to the tag handler instance at runtime.

For performance reasons, JSP engines will not necessarily instantiate a


new tag handler instance every time a tag is encountered in a JSP.
Instead, they may maintain a pool of tag instances, reusing them where
possible. When a tag is encountered in a JSP, the JSP engine will try to
find a Tag instance that is not being used, initialize it, use it and release it

69
J2EE Servlets & JSP

===========================================================================================================================
(but not destroy it), making it available for further use. The programmer
has no control over any pooling that may occur. The repeated use model
is similar to a servlet lifestyle, but note one very important difference; tag
handler implementations don’t need to concern themselves with threat
safety. The JSP engine will not use an instance of a tag handler to handle
a tag unless it is free. This is good news: as with JSP authoring in general,
developers need to worry about threading issues less often than when
developing sevlets.

6.3.1 The javax.servlet.Jsp.tagext.Tag Interface

The Tag interface defines a simple interaction between the JSP engine and the
tag handler, sufficient for tags that don’t need to manipulate their body content.
Its core methods are the calls implementing classes will receive when the JSP
engine encounters the tag’s opening and closing tags, doStartTag() and
doEndTag (). Before we look at the method contracts in more detail, a sequence
diagram helps to visualize the calls made to the tag handler by the compiled
servlet. Assume that the container already has a tag handler instance available,
and in the default state:

Let’s look at the messages in more detail:

 The container initializes the tag handler by setting the tag handler’s
pageContext property, which the tag handler can use to access
information available to the JSP currently using it.

 The container sets the tag handler’s parent property. (Parent may be set
to null, if the tag is not enclosed in another tag.)

 Any tag attributes defined by the developer will be set. This is a mapping
from the XML attributes of the tag to the corresponding properties of the
tag handler bean. For example, in the case of a tag invoked like this
<mytags:test name=”John” age=”43” />, the container will attempt to
call the setName() and setAge() methods on the tag handler. The
container will attempt to convert each attribute to the type of the
corresponding bean property: for example, the String “43” will be
converted to an int in this case. If the type conversion fails, an exception
will be thrown and must be handled by the calling JSP page. (From a JSP’s
point of view, there is no different between an exception thrown by a tag
handler and one thrown by an expression of scriptlet in the page.)

 Next, the container calls the tag handler’s doStartTag () method.

 The container calls the doEndTag () method.

 The container calls the release() method. This is not equivalent to a


finalizer. Tag handlers differ from page beans in that their lifecycle is
entirely independent of that of the JSPs that use them. Tag handlers must
support repeated use before destruction, possibly in a number of JSPs.
The implementation of the release() method must ensure that any state
that may cause conflict in future uses it reset, and that any resources
required during the tag’s execution are freed.

Lets look at the doStartTag() and doEndTag() methods:

int doStartTag() throws JspException

70
J2EE Servlets & JSP

===========================================================================================================================

Called after the tag has been initialized, when the JSP engine encounters the
opening of a tag at run time. Its return value should be one of two constants
defined in the Tag interface: EVAL_BODY_INCLUDE, which instructs the JSP
engine to evaluate both the tag’s body and any child tags it has, or SKIP_BODY,
which instructs the JSP engine to ignore the body. This can throw a JspException,
as will most of methods in the tag handler API when an error condition is
encountered; how it will be handled will depend on the JSP page using the tag.
Most JSP pages will use an error page, so an exception thrown in a tag will abort
the rendering of the page.

int doEndTag () throws JspException

doEndTag () is called when the JSP engine encounters the closing tag of an
element at run time. Its return value can be EVAL_PAGE or SKIP-PAGE.
EVAL_PAGE will cause the JSP engine to evaluate the rest of the page,
SKIP_PAGE to terminate evaluation of the page. The SKIP_PAGE return value
should be used only with very good reason; using tag handlers to terminate page
evaluation is even worse than sprinkling random return statements in Java code,
and may be confusing to the reader. A legitimate use might be to terminate page
output if it is established that the user has insufficient privileges to view the
whole of the page.

There are also a number of methods that related to tag nesting, initialization, and
reuse:

Tag getParent()
void setParent()

The specification also requires methods to expose the parent property. A tag’s
parent is the tag that directly encloses it in a JSP, or null if there is no enclosing
tag. Tag implementations can query their parent at runtime, to obtain context
information:

void setPageContext (PageContext pc)

setPageContext ( ) is an initialization method, making the PageContext of the JSP


available to the tag.

void release ( )

release ( ) is a call to the tag handler to release any resources. Examples of this
may be closing JDBC connections or open sockets that the handler requires for its
function and to clear any state associated with it. The second is an often
overlooked task in this context.

6.3.2 The javax.servlet.jsp.tagext.BodyTag Interface

BodyTag extends Tag, adding extra callbacks and other methods allowing the
developer to work with the content of the tag.

A sequence diagram displays the interaction between calling JSP and tag handler
in the case of a body tag; as you can see, it is somehow more complex than that
of the Tag interface:

71
J2EE Servlets & JSP

===========================================================================================================================
The extra steps involve the preservation of the JSP’s JSPWriter (messages 5 and
10), and the possibility of repeated calls to the doAfterBody( ) method, which
enables the BodyTag implementation to take control of the tag’s execution at
runtime.

The more significant methods of the BodyTag interface are listed below.

int doInitBody( ) throws JspException

Called after the tag has been initialized and doStartTag ( ) has been called. Its
return value should be EAVL_BODY_TAG, in which case the tag’s body content
and any child tags will be evaluated, or SKIP_BODY, in which case the body will
be ignored. Watch out that you don’t try to return EVAL_BODY_INCLUDE from a
BodyTag’s doInitBody ( ) or doStartTag ( ) methods. The JSP engine will throw a
JspException if it detected this.

int doAfterBody ( ) throws JspException

doAfterBody ( ) is called each time the tag’s body has been processed. The return
values are EVAL_BODY_TAG and SKIP_BODY. EVAL_BODY_TAG directs the JSP
engine to evaluate the tag’s body and any child tags again (resulting in at least
one more call to this method), SKIP_BODY, causes processing of the body
content to terminate. This can be used to conditionally loop through the tag
content.

void setBodyContent (BodyContent bodyContent)

Initialization method to set the class used to manipulate body content.

6.3.3 The javax.servlet.jsp.tagext.BodyContent Class

The BodyContent class is the key to BodyTag functionality. BodyContent is a


subclass of JspWriter that can be used to manipulate the body content of
BodyTag implementations and store it for later retrieval. The getBodyContent ( )
method of BodyTagSupport returns the BodyContent instance associated with a
particular tag.

To understand the way in which the BodyContent class works, consider how
JspWriter objects are handled in JSPs using BodyTags: messages 5 and 10 from
the sequence diagram above. Before the BodyTag begins to evaluate its body
content, the generated JSP implementation class includes the following line:

out = pageContext, pushBody ( );

After the BodyTag’s method have been called, it includes a matching call:

out = pageContext.popBody( );

What this means is that each BodyTag has a kind of play area, enabling it to
manipulate its BodyContent without automatically affecting the JspWriter of the
enclosing JSP page or tag. To generate output, the BodyTag needs to write the
contents of its BodyContent into its enclosing writer explicitly (see below). This is
the key difference between BodyTags and Tags: Tag implementations have no
such (flexibility, and therefore cannot modify or suppress their body content,

72
J2EE Servlets & JSP

===========================================================================================================================
although they can prevent it from being evaluated altogether by returning
SKIP_BODY in their implementation of doStartTag( ).

The most interesting methods in the BodyContent class are:

void clearBody( )

Clears the body content. Useful if we want to manipulate the body content before
writing it out.

JspWriter getEnclosingWriter( )

Returns the enclosing JspWriter; this may be the writer of an enclosing tag, or
the writer of a JSP itself. We normally use this method to get a JSP writer to
which we can write the body content stored in a body tag when we have finished
manipulating it. For example, we have used the following lines of code in the
doEndTag ( ) method of a number of BodyTag implementation in this chapter:

BodyContent bodyContent = getBodyContent ( );


if (bodyContent ! = null) {
bodyContent.getEnclosingWriter(), write(s)bout.toString());
}

This ensures that if there is any body content held in the body tag, it will be
written to the enclosing JSP writer.

String getString ( )

This returns the content already held in the body content, as a String. This is
useful if we need to examine what has been added to the body content with each
iteration of a loop.

6.3.4 Convenlence Classes

Some of the methods in Tag and BodyTag will be implemented the same way in
most tags. So the javax.servlet.jsp.tagext package includes two convenience
implementations of Tag and BodyTag: TagSupport and its subclass
BodyTagSupport. Classes implementing tag extensions will normally be derived
from one of these. The class diagram below shows the relationship between these
classes and the Tag and BodyTag interfaces:

TagSupport and BodyTagSupport are concrete, not abstract classes, so they


provide complete implementations of the corresponding interfaces, which do
nothing except return the appropriate values to cause the JSP engine to continue
rendering the page. So developers can safely omit methods that they are not
interested in. Developers don’t usually concern themselves with handling the
parent property and setPageContext ( ). The release ( ) method can also be
omitted if it is not necessary to free resource or return the tag to its default state.
The methods that a developer will normally want to override are doStartTag ( )
and doEndTag ( ) for all tags, and doInitBody ( ) and doAfterBody ( ) for
BodyTags specifically.

73
J2EE Servlets & JSP

===========================================================================================================================

TagSupport also makes an important convenience variable available to


subclasses: pageContext (the saved PageContext which was set by the JSP
engine when the tag was first used in a page). BodyTagSupport provides a
getBodyContent( ) method, necessary to obtain a tag’s BodyContent before
manipulating it.

Like me, you might find the names TagSupport and Body-TagSupport
confusing. These classes are standard implementations of the Tag and
BodyTag interface. It should be pointed out that this naming is
inconsistent with Sun’s usual practice and Java convention; I think of
them as TagImpl and BodyTagImpl.

6.3.5 The javax.servlet.jsp.tagext.TagExtraInfo Class

Metadata classes extending the TagExtraInfo abstract class may be associated


with tag handlers to provide extra information to a JSP engine. This optional
association is specified in the tag library descriptor.

We will look at the implementation of a TagExtraction class in more detail later in


this chapter, but the two methods you are most likely to override are:

VariableInfo[ ] getVariableinfo (TagData td)

This method is used to return information about scripting variable that the tag
makes available to JSPs using it. It returns an array of VariableInfo objects, which
contain information about the name of each scripting variable and its fully
qualified class name. It describes whether or not the variable should be declared
or whether the tag will merely overwrite the value of an existing variable, and the
scope of the variable.

Boolean isValid(TagData data)

This is sometimes used to validate the attributes passed to a tag at translation


time. As an example, consider a tag with four attributes. Three may be optional,
but if one of the optional attributes is specified the whole three must be present.
There is no way to specify this behavior in a tag library descriptor. However, the
isValid ( ) method of the appropriate TagExtraInfo subclass could be implemented
to return false if the parameters supplied at translation time are invalid. The
default implementation of isValid ( ) in TagExtraInfo always returns true. Note
that runtime attribute validation is entirely different, and is the responsibility of
the tag handler concerned.

6.3.5 Objects Available to Tag Handlers

All tag handlers have access to more context information than do most beans.
This is available through the PageContext object they are passed on initialization.
As you’ll recall, javax.servlet.jsp.PageContext is a convenient holder for
information about the runtime of a JSP page, including the request and response
object, and references to objects such as beans associated with the JSP.

This amount of access equals power. Note, though, that it is poor style to modify
request and response directly from a tag handler. Custom tags should be thought

74
J2EE Servlets & JSP

===========================================================================================================================
of as generic building blocks intended for use in a wide variety of contexts. In
practice tags should not be concerned with the parameters passed to the JSP
page. Although a tag handler can access request parameters, relying on doing so
will greatly reduce its reusability.

6.3.6 The Simple Example Revisited

To catch our breath after all this theory, let’s look again at the java
implementation of the simple example we introduced earlier. We see that the tag
handler extends TagSupport, and so gets most of its functionality for free. It has
no state and access no file or other resources, so there is no need to override
release( ). We use doEndTag ( ) to access the PageContext, obtain a JspWriter,
and generate output:

package tagext;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// Implementation of a tag to generate a single piece of HTML.


public class HelloTag extends TagSupport
{
// This method will be called when the JSP engine encounters the
start
// of a tag implemented by this class
public int doStartTag( ) throws JspTagException
{
// This return value means that the JSP engine should
evaluate
// the contents and any child tags of this tag
return EVAL_BODY_INCLUDE;
}
// This method will be called when the JSP engine encounters the
end //of a tag implemented by this class
public int doEndTag ( ) throws JspTagException
{
String dateString = new Date ( ). toString ( );
try
{
pageContext.getOut().write("Hello world <br/>");
pageContext.getOut().write("My name is " +
getClass().getName()+" and it's " + dateString + "<p/>");
}
catch (IOException ex)
{
throw new JspTagException("Fatal error: hello tag
could not write to JSP out");
}
// This return value means that the JSP engine should
continue to

75
J2EE Servlets & JSP

===========================================================================================================================
// evaluate the rest of this page
return EVAL_PAGE;
}
} // class HelloTag

Note that we need to check for IOException when generating output. Any
exception encountered while processing the tag must be wrapped as a
JspException if it is so to be rethrown; it is good practice to use the
javax.servlet.jsp.JspTagException subclass of JspException. (Note that,
confusingly, this isn’t in the same package as the other classes specific to tag
handlers.)

We could actually have omitted the doStartTag() method. I include it for


completeness, but in fact it does exactly what its superclass TagSupport’s
doStartTag() method does instruct the JSP engine to evaluate the tag’s content
and any subtags.

6.4 Tag Library Descriptors

Tag Library Descriptors or TLDs are XML documents with a .tld extension that
describe one or more tag extensions. TLDs must conform to the Document Type
Definition (DTD) included in the JSP 1.1 specification. Many of the elements are
intended to provide support for JSP authoring tools, although such tools are yet
to be widely available in the market.

The root elements are<taglib>. It’s defined in the DTD by:

<!ELEMENT taglib
(tlibversion, jspversion?,
shortname, uri?, info?,
tag+) >

 tlibversion is the version of the tag library implementation. This is defined


by the author of the tag library.

 jspversion is the version of JSP specification the tag library depends on.
At the time of writing the value you should use is 1.1 (the default). The
element is optional.

 shortname is a simple default name that could be used by a JSP authoring


tool; the best value to use is the preferred prefix value: that is, a
suggestion as to a prefix to use when importing the tag library. Although
there is no way of enforcing this, hopefully developers using the library ill
follow this suggestion, and consistency will be achieved between all users
of the tag library. The shortname should not contain whitespace, and
should not start with a digit or underscore.

 uri is an optional URI uniquely identifying this tag library. If it is used, the
value will normally be the URL of the definitive version of the tag library
descriptor.

 info is an arbitrary text string describing the tag library. Think of it as the
equivalent of a Javadoc comment relating to an entire class or package;
the authoring tool may display it when the tag library is imported.

The <tag> element is the most important. It’s defined in the DTD as:

76
J2EE Servlets & JSP

===========================================================================================================================

<!ELEMENT tag
(name, tagclass, teiclass?,
bodycontent?, info?, attribute?) >
 name is the name that will identify this tag (after the tag library prefix0.

 tagclass is the fully qualified name of the tag handler class that
implements this tag. This class must implement the
javax.servlet.jsp.tagext.Tag interface.

 teiclass stands for TagExtraInfo class, and defines the subclass of


javax.servlet.jsp.tagext.TagExtraInfo that will provide extra information
about this tag at runtime to the JSP. Not all tags require a TagExtraInfo
class.

 bodycontent is an optional attribute specifying the type of body content


the tag should have. Three values are legal: tagdependent, JSP, and
empty. The default (and more useful) to JSP, which means that the tag’s
body content will be evaluated at run time like any other JSP content.
tagdependent signifies that the JSP engine should not attempt to evaluate
the content, but accept that while it may not understand it, it means
something to the tag handler, and should therefore be passed unchanged.
empty is useful when a tag should not have any body content. If this value
is used, and the tag is not empty, JSP translation will fail.

<attribute> sub-elements describe each attribute accepted (or required) by the


tag. The DTD definition is:

<!ELEMENT attribute
(name, required?, rtexprevalue?) >

 name is the name of this attribute, as it will appear in JSPs using the tag.

 required specifies whether or not this attribute is mandatory. The valid


values are true/the attribute is required), and false (the default, signifying
an optional attribute). The attribute may have a default value.

 rtexprvalue specifies whether the attribute value can be the result of a JSP
expression, or whether it has a fixed value at translation time when the
tag is used in a JSP. Valid values are true and false. Again, the default is
false, meaning that expression are forbidden . If rtexprvalue is true, the
following will be legal.

<examples:mytag attrib”<%-myObject.getValue()%>’>

Allowing attributes to take expression values can be very useful. Setting


attributes by the use of expression allows their behavior to be determined
at runtime. For example, very often tag attributes will be set to the value
of properties of JSP beans. This relies on the use of a JSP expression.

The simple example’s TLD was very straightforward. As this tag takes no
attributes and has no associated TagExtraInfo class, only the bare minimum of
elements is required:

<?xml version=”1.0” encoding=”ISO-8859-1” ?>


<!DOCTYPE taglib

77
J2EE Servlets & JSP

===========================================================================================================================
PUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN”
http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_.dtd>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>examples></shortname>
<tag>
<name>hello></name>
<tagclass>tagext.HelloTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Simple example</info>
</tag>
</taglib>

Although the XML structure is not complex, and at present TLDs will
usually be written by hand, as JSP 1.1 becomes more widely supported
tool support can be accepted. This will synchronize TLDs and the relevant
Java classes, avoiding time-wasting trivial errors.

6.5 Using Tag Extensions in JSP Pages

Unlike the standard actions such as <jsp:forward>, custom tags must be


explicitly imported into JSP pages that wish to use them. The syntax for the taglib
directive is shown below:

<%@ taglib uri=”http//www.tagvendor.com/tags/tags.tld”


prefix=”example” %>

The uri attribute tells the JSP engine where to find the TLD for the tag library. The
prefix attribute tells the JSP engine what prefix will be given to tags from this
library in the remainder of the JSP.

A JSP may import any number of tag libraries. The taglib directive will cause an
exception at translation time if the tag library cannot be located; the first
attempted access to any tag defined in the TLD will cause an exception at runtime
if all the classes required to support the tag implementation cannot be loaded.

Once the tag library has been imported into the page, tags in a library can be
called as follows:

<examples:someTag name=”Rod”>
...
</examples:someTag>

The way in which custom tags are used in JSP is an example of Sun’s efforts to
introduce XML conventions into JSP syntax. Note that, unlike HTML attributes, the
attributes of custom tag must be enclosed in double quotes, in accordance with
the XML specification. (of course it is good practice to write XML complaint HTML
markup, but browsers do not currently enforce it.) Tag prefixes use the same
syntax as XML namespaces.

When a tag requires no body content, it is best to use the XML shorthand to make
this explicit:

<examples:hello name=”Rod” />

78
J2EE Servlets & JSP

===========================================================================================================================

Tag prefixes are defines in JSPs, not, as one might expect, in tag
libraries. Choice of prefix is a matter for developers, but consistency
among JSP pages importing the same tag library is advisable. It is best to
adopt the value of the shortname element in the tag library. The prefixes
jsp;, jspx;, java;, javax;, servlet;, sun;, and sunw: are reserved. It’s
perhaps unfortunate that Sun has not defined a unique naming system
such as the Java package naming system for tag library prefixes.
Choosing a prefix unique to a company or organization is advisable: for
example, instead of using the potentially clashing short name tables, it
might be advisable to use myCompany_tables.

6.6 Deploying the Packaging Tag Libraries

There are three main ways of deploying and using tag libraries with a JSP engine.
JSP developers must be familiar with all three, because each of them calls for
slightly different syntax in the taglib directive. (This means that JSPs need to be
modified slightly if they are to be deployed in a different way – surely an
oversight in the JSP specification.)

6.6.1 No Packaging

The first and simplest means of deployment is simply placing the tag library
descriptor under the server’s document root, and the Java classes required to
implement the tags in the server (or system) classpath. There is no attempt to
package a tag library or an application. In this case, the taglib directive will look
like this:

<%# taglib uri=”./hello.tld” prefix=”examples” %>

The uri is simply a path on the host server, which may be relative (as in this
example) or absolute. In this approach, the tag library descriptor (although not
the classes implementing the tag handler) is always publicly available: anyone
could view it by simply typing in its URL. This approach is easy to work with, but
can create problems at deployment time: the JSP engine or system’s classpath
has to be hand edited to include the classes implementing the tag.

6.6.2 WAR

In a second approach to deployment, the tag library descriptor, the Java classes
required to implement the tags, and the JSPs that use the tag library can be
shipped together as a web application, in a Web Archive file (better known a WAR
file). This is the approach we’ve taken in this chapter. It is very attractive
because it offers painless portability between servers and very easy deployment.
In this case, the taglib directive will look like this:

<%@ taglib uri=”/hello” prefix=”examples” %>

Note that we don’t specify the actual filename of the TLD, so there is no need to
use the TLD extension. This server knows where to look in the current web
applications WAR for a .tld file matching this URI because the mapping from URI
to file location is specified in the web.xml file in a <taglib> element. The
complete web.xml file for our simple example looked like this:

79
J2EE Servlets & JSP

===========================================================================================================================
<?xml version=”1.0” encoding=”UTF-8?>

<!DOCTYPE web-app PUBLIC `-//Sun MicroSystem, Inc.//DTD Web


Application 2.2//EN’’ http://java.sun.com/j2ee/dtds/web-app_2.2 .dtd’>

<web-app>
<display-name>tagext</display-name>
<description>Tag extensions examples</description>

<session-config>
<session-timeout>0</session-timeout>
</session-config>

<taglib>
<taglib-uri>/hellovar</taglib-uri>
<taglib-location>/WEB-INF/hello.tld</taglib-location>
</taglib>

</web-app>

The <taglib> element contains two subelements<taglib-uri> specifies the URI


that should be used is JSP’s wishing to use the tag library; <taglib>-location>
specifies the path to the tag library descriptor relative to be web.xml file. Note
that this path need not be publicly available to users of the web server; the
server will not publish anything that is in the WEB-INF directory.

Remember the important directories in the WAR.

 WEB-INF:
This contains the web.xml file, in which the TLD URI-location mapping
must be specified.

 WEB-INF/classes:
This contains Java classes required to implement tag libraries or otherwise
support the functionality of the web application.

 WEB-INF/lib:
This contains JAR files containing additional classes required to support the
functionality of the web application.

 WEB-INF/tlds:
By convention (although not mandated in any specification) this contain
the tag library description (but not tag handler classes) that will be made
available to JSPs in the web.xml file. The TLDs could actually be placed
anywhere in the WAR (so long as a mapping is included in the web.xml
file), but adhering to this convention makes it easier to comprehend the
WAR’s structure.

80
J2EE Servlets & JSP

===========================================================================================================================

Chapter: 7

JDBC

Topics Discussed

 Introduction to Databases
 Database Design
Two-Tier Database Design
Three-Tier Database Design
 Overview of ODBC (Open Database Connectivity)
 Overview of JDBC API
How does JDBC work?
Security Model
JDBC API Components
 The java.sql Package
 Literals
 Variables
 JDBC Drivers
Type 1: The JDBC-ODBC Bridge Driver
Type 2: The Native Library-to-Java Driver
Type 3: The Network Protocol Driver
Type 4: The Native Protocol Driver
 Executing SQL Commands Using JDBC drivers
Using Type 1 Driver (JDBC ODBC Bridge Driver)
Using Type 2 Driver (The Native Library-to-Java Driver)
Using Type 4 Driver (The Native Protocol Driver)
 The ResultSetMetaData Interface

7.1 Introduction to Databases

Data are raw facts from which information can be derived. A database is a record-
keeping system of an organization, more specifically a computer-based system,
the purpose of which is to record, and store data. A database can be defined as a
collection of stored operational data used by the application systems of some
particular enterprise.

A database is a collection of interrelated data from which some information


can be extracted. The collection of data must be logically coherent with some
inherent meaning. A database is designed and built for a specific purpose,
keeping in mind the needs of the applications that are going to use it and the end
users of those applications. A Database is like a data file, a data storage place.
Alike a data file, a database does not present information directly to a user. The
user runs an application that accesses data from the database and after analyzing
it, presents it to the user in a useful format. Databases systems are more
powerful than data files because data is more highly organized. In a well-
designed database, there are no duplicate pieces of data, the user or application
has to update at the same time. Related pieces of data are grouped together in a
single table, and the relationships between tables can be precisely defined. A
database typically has two components: the files holding the physical database
and the Database Management System (DMBS) software that application use

81
J2EE Servlets & JSP

===========================================================================================================================
to access, process, format, and output data. A DBMS is a general-purpose
software system that enables users to define and manipulate databases. It
provides an environment wherein data can be stored and retired from databases
easily and efficiently.

A Relational Database Management System (RDBMS) is a database based


on the relational model invented by E.F. Codd at IBM in 1970. It allows definition
of data structures, storage and retrieval operations and integrity constraints. An
RODMS can be thought of a DBMS with add on facility of setting relations
between databases, and hence at one instance of time you can use information
across tables.

7.2 Database Design

A Database Design can be categorized into three parts:

• Single Tier Database Design


• Two-Tier Database Design
• Three-Tier Database Design

Monolithic, Single Tier Database Design

In the beginning of the RDBMS era, the RDBMS applications were based on an
integrated model where the user interface code, application code, and the
database libraries were bundled together. The applications ran only on a local
machine and did not work on local-area networks. There was often, contention
between instances of the application because the monolithic approach did not
allow multiple instances of the application to communicate with each other. The
following figure depicts a monolithic, one-tier database design:

Application
Storage
Database
Libraries

Fig. 7.1
The one-tier database design

7.2.1 Two-Tier Database Design

The evolution of the two-tier design is due to the server technology. In this
model, the application accesses data through a server. The application is
considered as a front-end and the server as the back-end. The front-end
applications are stored in the client side and the database is stored on the server.
The client software is connected to the database through a socket connection.

In this model the clients send requests to the database server through SQL
(Structured Query Language). The server sends the results according to the
request and the client is responsible for formatting the data. The communication

82
J2EE Servlets & JSP

===========================================================================================================================
between the client and server takes place with the help of a vendor-provided
library of functions. These functions are written in the C language.
The following figure depicts a two-tier database design.

Application (Client)

Client-side
Database
SQL Request
Server
Libraries

Storage

Fig.7.2
Two-Tier Database Design

7.2.2 Three-Tier Database Design

This design is not limited to only three tiers. In a multi-tier design, there is an
intermediate server in addition to the client and the database server. The client
communications with the intermediate server. The intermediate layer is used to
handle multiple client requests and manage the connection to one or more
database servers.
The following figure depicts the three-tier database design:

83
J2EE Servlets & JSP

===========================================================================================================================

Middleware
Application (Client)
Datab
Business
ase
Rules
Server
Client-side
Libraries Client-side
Libraries
Data Reply

Change
Notification

Storage

Fig. 7.3
Three-Tier Database Design

Since, every organization maintains data pertaining to its business, employees,


and clients in a database using some DBMS or ROBMS package, it is of vital
importance that we have some mechanism to connect to the database using the
programming languages at our disposal. Over the years we have had many
approaches to establish connection with database but a few have stood the test
of time. Let us go through a few of the more successful approaches for database
connectivity.

Note In two-tier and three-tier systems, an application is logically divided into


three parts:

• GUL, Graphical User Interface: Consists of screens, Windows, buttons, list


boxes and more.
• Business Logic: This is the part of the program that deals with interaction
between various data elements, for example, calculation or credit limit based
on the annual salary, etc.

84
J2EE Servlets & JSP

===========================================================================================================================

• DBMS The database management system, that deals with the actual storage
and retrieval of data.

7.3 Overview of ODBC (Open Database Connectivity)

ODBC is a database interface used to interact with databases from a


programming language through its functions. It is Microsoft’s implementation of
the X/Open and SQL Access Group (SAG) Call Level interface (CLI) specification.
The functions of ODBC include adding, modifying and deleting data and obtaining
details about the databases, tables, views, and indexes. An ODMC application has
five layers (shown in Figure 7.4):
• Application Layer
• ODBC Interface Layer
• Driver Manager Layer
• Driver Layer
• Data Source Layer

Application

ODBC

Driver Manager

Driver

Data Source

Fig. 7.4
ODBC Architecture

• Application Layer

The Application Layer provides GUI and Business logic, written in languages like
Java, Visual Basic and C++.

• ODBC Layer

The Application layer uses the ODBC functions defined in the ODBC interface to
interact with the databases.

• Driver Manager Layer

The Driver Manager Layer manages the loading of various drivers available in the
system, directing calls to the right driver, and providing driver information to the
application when required. The driver manager ensures that the right database
management system gets all the program calls directed to it and that the data
from the data source is routed to the application when an application is connected
to more than one database.

• Driver Layer

85
J2EE Servlets & JSP

===========================================================================================================================

This layer is the actual component, which knows about specific databases. The
driver is assigned to a specific database like the Access Driver, SQL Server Driver,
and Oracle Driver. It is the duty of Driver Layer to implement all the functionality
provided by the ODBC interface like SQL statement calls, connection management
calls, information about the database and so on. This indicates that the Driver has
to emulate the ODBC interface functions not supported by the underlying DBMC
for some databases. The other duties of this layer include sending queries to the
databases, receiving the data back, and routing the data to the application. The
Driver layer also handles the network communication for databases that are in
the local networked system or on the internet.

• Data Source Layer

In the content of ODMC, the Data Source can be a database management


system, or the data store, which is usually a set of files on the hard disk. It can
be the Microsoft Access database, the SQL Server database or the Oracle
database.

7.4 Overview of JDBC API

JDBC stands for Java Database Connectivity. It was developed by JavaSoft and is
a part of the Java Enterprises API. JDBC is the first standardized API that allows
the users to develop database front ends without continuously rewriting their
code. JDBC provides the ability to create robust, platform-independent
applications and Web-based applets, which can access any database through a
DBMS-independent mechanism. The interaction between these applications and
applets with SQL data sources is done through a set of relation database objects
and methods defined in the JDBC API.

7.4.1 How does JDBC work?

A set of API objects and methods, defined in JDBC, are used to interact with the
underlying database. At the beginning of the process, a Java program open a
connection to a database. Then, it creates a statement object, passes SQL
statements to the underlying DBMS through the statement object, and retrieves
the results and information about the result sets. The JDBC class files and the
Java applets reside in the client. They can be downloaded from the network also.
It is better to have the JDBC classes in the client to minimize the latency during
execution. The DBMS and the data source are typically located in a remote
server. The applet and the JDBC layers communicate in the client system, and
interact with the database over the network.

7.4.2 Security Model

Security is very important especially when databases are involved. As far as JDBC
is concerned, it follows the standard security model in which applets can connect
only to the server from where they are loaded. Remote applets cannot connect to
local databases. Applications have no connection restrictions. The security check
is automatic as far as pure Java drivers are concerned. The drivers must have
security checks if they are developed through native methods.

86
J2EE Servlets & JSP

===========================================================================================================================
7.4.3 JDBC API Components

The JDBC API has two levels of interface: the Application Layer and the Drive
Layer. The Application Layer allows the developer to make calls to the database
via SQL and retrieve the results. The Driver Layer handles communication with a
specific driver implementation. The Driver Layer must implement for interfaces
and one class. The class bridges the Application Layer and the Drive Layer. The
four interfaces are Driver, Connection, Statement, and ResultSet. The connection
to the database is made by the Driver interface. The developer has one more
layer of abstraction, i.e. the DriverManager Class. In most applications, the
Driver is accessed through the DriverManager class.

The interfaces like Connection, Statement and ResultSet represent methods that
allow the developer to create statements and retrieve results. The Driver and
Application layers allows the developer to create database applications without
knowing details i.e., from where the objects are coming or what type of driver the
application will use. The following section describes about the implementation of
the JOBC API classes and interfaces.

7.5 The java.sql Package

The implement of JDBC is made through the java.sql package. This package
contains all the JDBC classes and methods that allow the developer to create
database applications. The topmost class in the class hierarchy of JDBC classes is
the Driver/Manager, which keeps to our information, state information and more.
When each driver is loaded, it is registered with the DriverManager. Whenever a
connection is made, the Driver/manager selects the driver on the JDBC URL.

The JDBC URL is a string that is used by the drivers and access databases. The
syntax of a JDBC URL is:

jdbc:<subprotocol>:<subname>

The <subprotocol> defines the type of driver and <subname> provides the
network-encoded name. For example:

jdbc:oracle:customer

In the above example, the database driver is an Oracle driver and the subname is
a local database called customer.

For databases on the Internet or intranet, the subname can contain the net
URL //hostname:port/. For example

jdbc:msq1:.//dbserver.eng:812/burgerports

In the above example, the mysql is the database driver type, which locates a
server named dbserver in the eng domain and attempts to connect to a database
server on the port 812 that contains a burgerports database using the default
username and password.

• The java-sql.Driver Interface

JDBC drivers implement the Driver interface. Writing a JDBC driver consists of a
creating a Java class that implements the Driver interface. Although you do not

87
J2EE Servlets & JSP

===========================================================================================================================
have to worry about writing your own JDBC driver. Table below lists the methods
defined in this class.

Methods Description
Connection connect(String This method first checks the sub-protocol name of
url, Properties into) the URL string passed for a match this driver. The
throws SQLException Driver then attempts to make a connection to the
database using the remaining part of the URL. If the
connection is successful, this method will return an
instance of the Connection class. It throws an
SQLException only if the driver recognizes the URL
subprotocol but cannot make the database
connection. The second parameter info contains the
username and password.
Boolean The method returns true only if the URL is valid. It
acceptsURL(String url) checks only the sub-protocol specified in the URL,
throws SOLException not whether the connection can be made.

The most important method is the connect( ) method, which is invoked for the
driver by the Driver/Manager to obtain a Connection object is the starting point of
the JDBC Application. This object is used to create Statement objects that
perform the queries.

• The DriverManager class (java.sql.DriverManager)

This class controls the coding of driver specific classes. The JDBC drivers are
actually managed by the utility class. DriverManager. This class provides methods
that allow the user to obtain a connection through a driver, register and de-
register drivers, set up logging, and set login timeouts for database access. As
the methods in this class are static and hence they have to be referred to through
the class name. Table below lists the methods defined in this class:

Methods Description
Connection This method returns a reference to a Connection
getConnection( String url, object implemented from the Connection interface.
Properties info ) throws The parameter info is a reference to a Properties
SQLException object, which contains the username and password.
Connection This method returns a Connection object by calling
getConnection(String url) the getConnection(url,info) with the empty
throws SQLException Properties object (info).
Connection This method first creates a Properties object (info),
getConnection( String url, stores the user and password strings into it and then
String user, String calls getConnection (url, info).
password) throws
SQLException
void registerDriver This method stores the instance of the Driver into a
vector of drivers along with an instance of
(Java.sql.Driver driver) SecurityContext, which identifies where the driver
throws SQLException came from.
void This method sets a private, static
setLogStream( java.io.Prin java.io.PrintStream reference to the PrintStream
tStream out) object passed to the method.

The drivers are registered with the Drive/Manager at the time of initialization of
the DriverManager class or at the time of creating an instance of the driver.
Actually, each driver name is a class filename and these class names of drivers

88
J2EE Servlets & JSP

===========================================================================================================================
are listed in a Java property named jdbc.drivers, which are loaded when the
DriverManager class is loaded. This property can be used to define a list of colon-
separated driver class names, such as;

jdbc.driver=imaginary.sql.Driver:oracle.sql.Driver:weblogic.
sql.Driver

The DriverManager uses the following call to locate, load, and link the named
classes through the current CLASSPATH:

Class.forName (driver);

The application must create an instance of a driver class if the jdbc.drivers


property is unspecified. The driver class is created by implementing the interface
Driver. In both cases, the implementation of the Driver class must register itself
with the DriverManager by calling the registerDriver() method, as follows:

DriverManager.registerDriver (this);

• The Connection interface

One of the major interface in JDBC API is the connection interface, which
represents a session with the database connection provided by the Driver. The
functionalities of this class range from transaction processing to creating
statements. Once the user gets a Connection object form the driver, the user
should set the auto-commit mode of false since JDBC connections are in auto-
commit mode by default. The connection will support commit and rollback
methods when the auto-commit mode is disabled. Table below lists the method
defined in this class:

Methods Description
Statement This method returns a Statement object, which is
createStatement() throws then used to issue queries.
SQLException
PrepareStatement This method returns a PrepareStatement object that
prepareStatement is configured with the sql string. The Driver may
( String sql ) throws then send the statement to the database, if the
SQLException database(driver) handles precompiled statements.
Otherwise, the driver may wait until the
PreparedStatement is executed by an execute
method. The SQLException might be thrown if the
driver and the database do not implement
precompiled statements.
CallableStatement This method returns a CallableStatement object,
prepareCall(String sq ) which is used to handle stored procedures. The sql
throws SQLException string is sent immediately through the driver when
prepareCall() is complete or may wait until an
execute method occurs.
void This method is used to set a flag in the driver that
setAutoCommit( Boolea enables commit (true)/rollback(false) or makes all
n commit-mode ) transactions commit immediately.
throws SQLException
void commit() throws This method takes care of all changes made since
SQLException the beginning of the current transaction.
void rollback() throws This method is used to drop all changes made since
SQLException the beginning of the current transaction.

89
J2EE Servlets & JSP

===========================================================================================================================
DatabaseMetaData This method is used to return a DatabaseMetaData
getMetaData() object which is associated with the information about
the whole database, including access information
about tables and procedures, column names,
datatypes and so on.

• The Statement interface

The Statement object is used to interact with the Database Management System
in terms of SQL statements. In other words, the statement object sends the SQL
queries to the database and retrieves results. The user can create many
Statement objects from the Connection object. The Statement object is
associated with various data needed to interact with a database, including state
information, buffer handles, and so on. But these are transparent to the JDBC
application program. Statements can be SQL updates, insertions, deletions or
queries. Table below lists the methods defined in the Statement interface that
allow the developer to make the job of writing queries to the database easier.

Methods Description
ResultSet This method is used to execute a SQL query and return
executeQuery (String a ResultSet object.
sql0 throws
SQLException
int This method is used to execute a SQL query and return
executeUpdate( Strin an integer that represents the affected rows. This
g sql ) throws method can be used in situations where no results are
SQLException expected except a row-count status.
boolean execute(String This method can be used when a SQL statement returns
sql ) throws single or multiple result sets or update counts. This
SQLException method can also be used to execute stored procedures
that return Out and InOut parameters. To retrieve the
data returned, the methods getResultSet(),
getUpdateCount(), and getMoreResults() are used.
ResultSet This method is used to return the current data as the
getResultSet() throws result of a statement execution in the form of a
SQLException ResultSet object. The method returns a null if there are
no results to be read or if the result is an update count.
The important point to note is that once the result is
read, it is cleared.
int getUpdateCount() This method returns the status of an Update, Insert,
throws SQLException and Delete query or a stored procedure that returns a
row status. The method returns –1 if there is no update
count or the data returned is a result set. The update
count will be cleared once it is read.
boolean This method is used to return true if the next result is a
getMoreResults() ResultSet object. The method moves to the next result
throws SQLException in a set of multiple results/update counts. once read,
the previous ResultSet will be closed.

JDBC supports two more types of statement objects in addition to the statement
object. They are PreparedStatement and CallableStatement.
In the case of a PreparedStatement object, as the name implies, the application
program prepares a SQL statement using the
java.sql.Connection.prepareStatement() method. The PrepareStatement()
method takes a SQL string, which is passed to the underlying DBMS. The DBMS

90
J2EE Servlets & JSP

===========================================================================================================================
goes through the syntax run query plan optimization, and the execution plan that
the JDBC driver stores internally in the Prepare/Statement object.

The methods of the PreparedStatement object such as executeQuery(),


executeUpdate(), and execute() methods are just calls to the underlying DBMS to
perform the already-optimized SQL statement.

For a secure, consistent, and manageable multi-tier client/server system, to data


access should allow the use of stored procedures. Stored procedure centralizes
the business logic in terms of manageability and also in terms of running the
query. Java applets running on clients with limited resources cannot be expected
to run huge queries. But the results are important to those clients. JDBC allows
the use of stored procedures, by the CallableStatement interface, with the escape
clause string.
A Callable/Statement object is created by the prepareCall() method in the
Connection object. The prepareCall() method takes a string as the parameter.
This string, called an escape clause, is of the form

{[?=] call <stored procedure name> [<parameter>,<parameter> . . .]}

where the question mark symbol(?) is the placeholder for the parameters/

The CallableStatement interface supports parameters. These parameters are of


the OUT kind from a stored procedure or the IN kind to pass values into a stored
procedure. The parameter marker (question mark) must be used for the return
value (if any) and output arguments because the parameter marker is bound to a
program variable in the stored procedure, input arguments can be either literals
or parameters. For a dynamic parameterized statement, the escape clause string
takes the from

{[“=] call <stored procedure name> [<?>, <?> …]}

The OUT parameters should be registered using the registerOutParameter()


method as shown in table below before the call to the executeQuery(),
executeUpdate(), or execute() methods.

In the JDBC call, you create a CallableStatement object with the “?” symbol as a
placeholder for parameter, and then connect Java variables to the parameters.

Methods Description
void This method is used to tie the placeholders with actual
registerOutParameter parameters. The argument parameterIndex depicts the
(int parameterIndex, position of the question marks and SqlType defines the
int sqlType) SQL datatypes that are returned as Out parameters.

The CallableStatement interface defines the getType methods and the


PrepareStatement interface defines the setType methods. The setType methods
are used to set the values of the parameters marked in the SQL statements with
question marks (?) whereas the getType methods are used to convert the SQL
types returned from the database to Java types. Tables below defines the
setType methods and the getType methods.

setType Methods

Method Java Type SQL Type

91
J2EE Servlets & JSP

===========================================================================================================================
void setByte(int index, byte b) Byte TINYINT

void setShort(int index, short x) short SMALLINT


void setInt(int index, int I) int INTEGER
void setLong(int index, int I) long BIGINT
void setFloat(int index, int f) float FLOAT
void setDouble(int index, int d) double DOUBLE
void setBigDecimal9int index, java.lang.BigDecimal NUMERIC
BigDecimal x)
void setString(int index, String s) java.lang.String VARCHAR
void setAsciiStream(int jav.io.InputStream
index,InputStream x, int length)
void setUnicodeStream(int index, java.io.InputStream LONGVARCHAR
InputStream x, int length)
void setBytes(int index, byte x[]) byte array VARBINARY
void setBinaryStream(int index, java.jo.InputStream LONGVARBINARY
InputStream x, int length)
void setDate(int Index, Date d) java.sql.Date DATE
void setTime(int index, Time t) java.sql.Time TIME
void setTimestamp(int index, java.sql.TimeStamp TIMESTAMP
Timestamp ts)
void setNull(int index, int sqlType) java.sql.Types
has contains for
each of the SQL
types.
void setBoolean(int index, boolean boolean BIT
b)

getType Methods

Method Java Type SQL Type


boolean getBoolean(int Boolean BIT
index)
byte getByte(int index) Byte TINYBIT
short getShort(int index) short SMALLINT
int getInt(int index) int INTEGER
long getLong(int index) int BIGINT
float getFloat(int index) float FLOAT
double getDouble(int double DOUBLE
index)
BigDecimal java.lang.BigDecimal NUMERIC
getBigDecimal(int index,
int scale)
String getString(int string CHAR, VARCHAR, or
index) LONGAVARCHAR
byte[] getBytes(int Byte array BINARY, or VARBINARY
index)
Date getDate(int index) java.sql.Date DATE
Time getTime(int index) java.sql.Time TIME
TimeStamp java.sql.Timestamp TIMESTAMPA
getTimeStamp(int index)

• The ResultSet interface (java.sql.ResultSet)

92
J2EE Servlets & JSP

===========================================================================================================================
The data from tables are accessed through the methods defined in the ResultSet
interface. Actually the data from tables are generated by executing Statement.
This class stores the results of the statements created. The ResultSet column
values are indexed and hence they may be accessed in any order. Also, they can
be selected either by name or the number of the column. The ResultSet values
are indexed and hence they may be accessed in any order. Also, they can be
selected either by name or the number of the column. The ResultSet object
maintains a cursor indicating the position of the current row. Table below defines
the methods of the ResultSet interface.

Method Description
boolean next() throws This method sets the position of the ResultSet to the
SQLException next row. Initially the ResultSet row position is the first
row of the result set.
ResultSetMetaData This method is used to main an object this is associated
getMetaData() throws with the description of the current result set. The
SQLException description includes the number of columns, the type of
each column, and properties of the results.
void close(0 throws This method is used to release the resources associated
SQLException with the ResultSet.

Now that you have been introduced to the various classes and interfaces of JDBC
APL. Before explaining the examples, which demonstrates the usage of the
methods, you must be clear with the JDBC drives through which the JDBC
application runs.

7.6 JDBC Drivers

There are a number of drivers available from database vendors and third-party
developers. But, it is always wise to have the drivers that have the best features,
are cost effective and provide customer support. There are a variety of drivers
available according to the type of database they are intending to support.
JavaSoft categorizes database drivers in four ways:

7.6.1 Type 1: The JDBC-ODBC Bridge Driver

The first type of JDBC driver is the JDBC-ODBC Bridge. This driver type is
provided by Sun with the JDK1.1 and later. It is a driver that provides access to
database through ODBC drivers. For that the ODBC driver must be configured on
the client for bridge to work.

Developers can use the JDBC-ODBC bridge driver instead of other JDBC drivers
since applications will speak directly to JDBC interface classes. Also, developers
should be aware of the requirements to run the applications when the JDBC-
ODBC bridge is implemented and the clients must have a local copy of the ODBC
driver, the ODBC driver manager, and client-side libraries since ODBC calls are
made using binary C calls. Figure 7.6 shows the driver interaction of the JDBC-
ODBC Bridge.

7.6.2 Type 2: The Native Library-to-Java Driver

93
J2EE Servlets & JSP

===========================================================================================================================

To translate JDBC to the native client library, the Native Library-to-Java Driver
uses native C language library calls. These drivers use C language libraries that
provide vendor-specific functionality and tie these libraries to the JDBC. These
drivers were first available for Oracle, Sybase, Informix, and other client-library-
based RDBMSs. Figure 7.6 shows the interaction of the Native Library-to-Java
Drive.

Application
Java Space
Application

Type 2 Jdbc Driver


SQL
Native Database Library
Command Result
Set

Proprietary
Protocol

Library
Database

Fig. 7.6
The Native library-to-Java Driver

7.6.3 Type 3: The Network Protocol Driver

The JDBC-Network protocol drivers are a three-tier solution. This type of driver
translates JDBC calls into a database-independent network protocol that is sent to
a middleware server. This server then translates this DBMS-independent protocol
into a DBMS-specific protocol, which is sent to a particular database. The result is
routed back through the middleware server and sent back to the client. This type
of solution makes it possible to implement a pure Java client. It makes it possible
to swap database without affecting the client. This is by far the most flexible
JDBC solution.

94
J2EE Servlets & JSP

===========================================================================================================================

Java Application
Application Space

SQL
Type 3 Jdbc Driver
Command Result
Set

Middleware Space
JDBC Driver
Proprietary
Protocol

Database

Fig. 7.7
The Network protocol Driver

7.6.4 Type 4: The Native Protocol Driver

The Type 4 drivers are pure Java drivers that communicate directly with the
vendor’s database. This is done through converting JDBC commands directly into
the database engine’s native protocol. The type 4 Driver has a very distinct
advantage over all the other driver types. It has no additional middleware layer,
which improves performance tremendously. Figure 2.8 shows the communication
of a Type 4 driver.

Application
Java Application Space

Type 4 JDBC Driver

SQL Command Result


Using Proprietary Using Proprietary
Protocol Protocol
Database

Fig. 7.8

95
J2EE Servlets & JSP

===========================================================================================================================
The Native Protocol Driver

7.7 Executing SQL Commands Using JDBC drivers

7.7.1 Using Type 1 Driver(JDBC ODBC Bridge Driver)

Before you start writing the programs using Type 1 Drivers, create a table inside
the Oracle database with the name emp. Add fields ENAME, EMPNO, DESIG,
HIREDATE and DEPTNO.

Now let us start making the programs

• Program to retrieve the result from the Table

The following program executes a SQL SELECT statement to list all the employee
in the database.

import java.sql.*;
class sqldemo1
{
public static void main(String a[] ) throws Exception
{
int StNo;
String StName;
Connection Conn;
Statement Stmt;
ResultSet rs;
//Initialize and load the JDBC-ODBC driver.
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
// To get a database connection
Conn =DriverManager.getConnection("jdbc:odbc:empDB");
//To create a statement object to execute the SQL statement
Stmt = Conn.createStatement();
//Sends the SQL statement to the DBMS and executive
rs = Stmt.executeQuery("select empno, empname from emp");
//Processing the results
System.out.println("Empno "+" Name ");
while(rs.next())
{
StNo = rs.getInt(1);
StName = rs.getString(2);
System.out.println(StNo+"\t"+StName);
}
}
}
The output is as shown in Figure 7.9.

Fig. 7.9

96
J2EE Servlets & JSP

===========================================================================================================================
Output of the program

While creating the above program, the following steps have been followed:

Step 1: The program initializes and loads the JDBC-ODBC driver using the static
method forName() of the class Class.

Step 2: The program calls the getConnection() method to get the Connection
object.

Step 3: With the help of the object created in step 2, it invokes the method
createStatement() to create the Statement object and prepares SQL treatment.

Step 4: With the help of the Statement object, you then invoked the
executeQuery() method of the Statement interface, passing it the Select empno
and empname From emp SOL statement as an argument. This resulted in the
query being processed by the database and a ResultSet object being returned.

Step 5: A ResultSet object maintains a pointer to a row within the tabular


results. The pointer is referred to as a cursor. When a ResultSet object is
returned from a query, the cursor initially points immediately before the first row
of the table. The next () method of the ResultSet interface is used to move the
cursor to the next row of the table. The next () method returns a boolean value is
true if the next row is returned and false it the end of the table is reached. Hence,
each how is processed until there are no more rows.

Note: The odbc subprotocol name is reserved for ODBC style data sources. A
normal
ODBC databases JDBC URL locks like the following:

jdbc:odbc:<ODBC DSN>;User=<username>;PW=<password>

That is, when you use the jdbc:odbc driver, the JDBC url should contain a data
source name (DSN), user ID, and password for the ODBC data source. It must be
initialized and loaded with the following method as described earlier:

Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);

In the next example the first three steps will be the same.

• Program to Update the Table

The following program is used to update the name and addr of the student whose
number is 2.

import java.sql.*;
class OraSqlUpdate
{
public static void main(String a[] ) throws Exception
{
int StNo;
String StName;
Connection Conn;
Statement Stmt;
ResultSet rs;
//Initialize and load the JDBC-ODBC driver.

97
J2EE Servlets & JSP

===========================================================================================================================

Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

// To get a database connection


Conn =DriverManager.getConnection("jdbc:odbc:OraDsn","scott","tiger");
//To create a statement object to execute the SQL statement
Stmt = Conn.createStatement();
//Sends the SQL statement to the DBMS and executive
int n= Stmt.executeUpdate("Update stud set name='yanu', addr='China'
where no=2");
System.out.println("Number of records updated is "+n);
}
}

The output is as shown in Figure 7.10.

Fig. 7.10
Output of the program

In the code given above, the UpdateName () method has been created, which
updates the empno and empname of a particular employee, whose name is
passed as an argument.

While creating the above program the first three steps, which we followed in the
previous example, are the same. The only difference is in fourth and fifth step.
Here instead of executeQuery(), the method executeUpdate() has been invoked.
The executeUpdate() method of the Statement interface takes in the SQL Update
statement as an argument and returns an integer value representing the number
of rows updated. In the above code it returns 1.

The following section describes the usage of PreparedStatement and


CallableStatement interfaces in programs. As discussed earlier, the
PrepareStatement interface provides an efficient mechanism for passing a
precompiled SQL statement that uses parameters. You have to use the setType
methods defined in Table 1.6 in the following programs, since the
PreparedStatement parameters are considered as In (input) parameters and they
have to filled in using the setType methods.

• Programs to insert the row using PreparedStatement interface

98
J2EE Servlets & JSP

===========================================================================================================================
The following program inserts rows in the Students table where you can see the
usage of the PreparedStatement parameters:

import java.sql.*;
public class preparedmo1
{
public static void main(String a[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:OraDsn",
"scott", "tiger");
PreparedStatement p1 = c.prepareStatement("Create table
Empl(Name varchar2(30),No number(10))");
p1.executeUpdate();
PreparedStatement p = c.prepareStatement ("insert into Empl
values(?, ?)");

p.setString (1, "soma");


p.setInt (2,1000);
p.executeUpdate();

System.out.println("value inserted");
}
}

The output is as shown in Figure 7.8.

Fig. 7.8
Output of the program

In the code given above, after initializing and loading the Driver the
prepareStatement() method is invoked using the object of the Connection
interface. This method returns the object of the PreparedStatement interface,
which is used with parameterized SQL statements. These parameterized SQL
statements replace a constant SQL statement with a question mark(?), which is
called an IN parameter. The PreparedStatement provides several set methods
for setting the values of IN PARAMETERS. These methods are organized into the
type of value to which a parameter is to be set.
Further, the executeUpdate() method of the PreparedStatement interface has
been invoked to execute the SQL statement, which is passed as an argument to
the prepareStatement() method.

• Program to invoke a stored procedure using CallableStatement


interface

99
J2EE Servlets & JSP

===========================================================================================================================
Now, we will see the usage of the CallableStatement interface. As discussed
earlier, this interface allows the developer to execute SQL stored procedures and
pass IN and OUT parameters. Since the CallableStatement inherits the method
from the Preparedstatement interface, all of the execute and setType methods
are available. The following example will demonstrate the method of passing IN
and OUT parameters to stored procedures and executing them.

import java.sql.*;
import java.io.*;
class caloric
{
public static void main(String a[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:OraDsn","scott","tiger");
CallableStatement c1 = con.prepareCall ("{call selectpro (?, ?)}");
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the no");
int p1= Integer.parseInt(b.readLine());
c1.setInt(1, p1);
c1.registerOutParameter(2, Types.VARCHAR);
c1.execute();
String output =c1.getString(2);
System.out.println("The name selected for the given number is
"+output);
}
}

To run the program given above follow the steps given below:

Step 1:
create or replace procedure
selectpro (num in number, nam out varchar2 )
is
begin
select name into nam from stud where no=num;
end;

Step 2: Create a DSN(data source name)

Step 3: Compile the program using javac

Step 4: Run the program using java

Step 5: In the command promptness pass the empno. You will get the
corresponding deptno

The output is as shown in Figure 7.12.

100
J2EE Servlets & JSP

===========================================================================================================================

Fig. 7.12
Output of the program

In the above program after initializing and loading the driver, the method
prepareCall() of the Connection interface has been invoked to create the object of
CallableStatement. The stored SQL procedure is passed as an argument to the
prepareCall() method. It is parameterized using question marks in the same
manner as that discussed for the PreparedStatement interface.

7.7.2 Using Type 2 Driver (The Native Library-to-Java Driver)

Before executing JDBC codes through Type 2 and Type 4, you must copy one of
the two files called clsses81.zip and classes101.zip to the folder from where
you are running the codes and set the classpath to that folder. These files are
present inside the folder Oracle\Ora8i\jbdc\lib.

While creating the codes for Type 2 and Type 4 drivers, except the first two all
the steps are same. Here you have to load and register the driver by specifying
the classname oracle.jdbc.driver.OracleDriver where the specification of both
Type 2 and Type 4 drivers are available. Secondly, you have to specify the
driver name, which is passed as an argument with the getConnection() method.

The code given below demonstrates the usage of the Native Library-to-Java
Driver: In this code we are creating a new table, inserting a record it and finally
displaying the record.

import java.sql.*;
class orasql
{
public static void main(String ar[])
{
try
{
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection
("jdbc:oracle:oci8:@","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from dept");
while(rs.next())
{
System.out.println(rs.getInt(1)+" : "+rs.getString(2)+" :
"+rs.getString(3));
}
}catch(Exception e) {e.printStackTrace(); }
}

101
J2EE Servlets & JSP

===========================================================================================================================
}

7.7.3 Using Type 4 Driver (The Native Protocol Driver)

The code given below demonstrates the usage of Native Protocol Driver. The
following code displays all the name of the employees from the table emp.

import java.sql.*;
class sqldemo1
{
public static void main(String a[] ) throws Exception
{
int StNo;
String StName;
Connection Conn;
Statement Stmt;
ResultSet rs;
//Initialize and load the JDBC-ODBC driver.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// To get a database connection
Conn
=DriverManager.getConnection("jdbc:odbc:thin:@dhs04:1521:dhs04db","scott","
tiger");
//To create a statement object to execute the SQL statement
Stmt = Conn.createStatement();
//Sends the SQL statement to the DBMS and executive
rs = Stmt.executeQuery("select empno, ename from emp");
//Processing the results
System.out.println("Empno "+" Name ");
while(rs.next())
{
StNo = rs.getInt(1);
StName = rs.getString(2);
System.out.println(StNo+"\t"+StName);
}
}
}

7.8 The ResultSetMetaData Interface

The java.sq1 package contains two MetaData interfaces, the DatabaseMetaData


and the ResultSetMetaData interface. The DatabaseMetaData interface is used to
obtain information about a database such as a list of all tables in the database,
system functions, keywords, database product name, and the name of the JDBC
driver supported by the database. The ResultSetMetaData interface is used to
obtain information about the columns stored in a ResultSet object such as the
datatype, the column heading, and the properties of each column. The following
table explains some of the methods of the ResultSetMetaData interface.

Method Description
int getColumnCount ( ) Returns the number of columns stored
in a ResultSet object
String getColumnName (int Returns the column name of the
column_number) specified column
String getColumnTypeName (int Returns the database specific datatype

102
J2EE Servlets & JSP

===========================================================================================================================
column_number) of the specified column.

You use the getMetaData ( ) method of the ResultSet class to obtain a reference
to the ResultSetMetaData object of a particular result set.

Example:
import java.sql.*;
public class QueryApp
{
public static void main(String a [ ])
{
ResultSet result;
String rowdata="";
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:OraDsn", "scott", "tiger" );
Statement stat=con.createStatement();
result=stat.executeQuery("Select name,addr from stud");
ResultSetMetaData rsmd=result.getMetaData( );
int colCount=rsmd.getColumnCount ( );
//Code to retrieve and display the column headings
/* The String.trim ( ) method is used to remove leading and
trailing blanks in a string */
for (int i=1; i<=colCount; i++)
{
rowdata=rowdata+" :
"+rsmd.getColumnName(i).trim();
}
System.out.println (rowdata);

System.out.println("---------------------------------------------------");
rowdata=" ";
while (result.next())
{
//Code to retrieves and display each record of the result set
for (int i=1; i<=colCount; i++)
{
/* Retrieve the value present in the ith column of the
current row
*/
rowdata=rowdata+" :
"+result.getString(i).trim();
}
System.out.println(rowdata);
rowdata=" ";
System.out.println("\n");
}
}
catch (Exception e)
{
System.out.println ("Could not execute the query" +e);
}
}
}

103
J2EE Servlets & JSP

===========================================================================================================================

Glossary

104
Glossary
==========================================================================================================================

Glossary

Application Assembler

A person that combines components and modules into larger deployable


application units.

Application client

A first-tier client program that executes in its own Java Virtual Machine.

Application client container

A container that supports application clients and provides a federated view of the
J2EE platform APIs.

Application client module

A software unit that consists of one or more classes and an application client
deployment descriptor.

Application Component Provider

A vendor that provides the Java classes that implement components' methods,
JSP page definitions, and any required deployment descriptors.

APM

Application Programming Model. A programming model that defines how to use


and combine the features of the J2EE platform to create solutions for common
application domains in the enterprise.

Atomic

Refers to an operation that is never interrupted or left in an incomplete state


under any circumstance.

Authentication

The process by which an entity proves to another entity that it is acting on behalf
of a specific identity. The J2EE platform requires three types of authentication:
basic, form-based, and mutual.

Atomic

Refers to an operation that is never interrupted or left in an incomplete state


under any circumstance.

105
Glossary
==========================================================================================================================

Basic authentication

When a Web server authenticates an entity with a user name and password
obtained using the Web client's built-in authentication mechanism.

Bean

A reusable software component. Beans can be combined to create an application.

Bean-managed persistence

When the transfer of data between an entity bean instance's variables and the
underlying resource manager is managed by the entity bean.

Bean-managed transaction

When an enterprise bean defines the boundaries of the transaction.

Bean-managed transaction

When an enterprise bean defines the boundaries of the transaction.

Business logic

The code that implements the functionality of an application. In the Enterprise


JavaBeans model, this logic is implemented by the methods of an enterprise
bean.

Business method

A method of an enterprise bean that implements the business logic or rules of an


application.

Callback methods

Methods in a component called by the container to notify the component of


important events in its life cycle.

Classpath

A classpath is an environmental variable which tells the Java(TM) virtual


machine* and Java technology-based applications (for example, the tools located
in the JDK(TM) 1.1.X\bin directory) where to find the class libraries, including
user-defined class libraries.

Client

In the client/server model of communications, the client is a process that


remotely accesses resources of a compute server, such as compute power and
large memory capacity.

106
Glossary
==========================================================================================================================

Codebase

Works together with the code attribute in the <APPLET> tag to give a complete
specification of where to find the main applet class file: code specifies the name
of the file, and codebase specifies the URL of the directory containing the file.

Comment

In a program, explanatory text that is ignored by the compiler. In programs


written in the Java(TM) programming language, comments are delimited using //
or /*...*/.

Commit

The point in a transaction when all updates to any resources involved in the
transaction are made permanent.

Component

An application-level software unit supported by a container. Components are


configurable at deployment time. The J2EE platform defines four types of
components: enterprise beans, Web components, applets, and application clients.

Component contract

The contract between a component and its container. The contract includes: life
cycle management of the component, a context interface that the instance uses
to obtain various information and services from its container, and a list of
services that every container must provide for its components.

Component environment

A set of requirements defined by the Application Component Provider required to


be available to a J2EE component in its naming environment. The environment
entries are declaratively specified in the component's deployment descriptor.
Each component names and accesses its environment configuration values using
the java:comp/env JNDI context. These values can be objects a component is
dependent on, such as a JDBC DataSource or a simple value such as a tax rate.

Container-managed persistence

When transfer of data between an entity bean's variables and the underlying
resource manager is managed by the enterprise bean's container.

Container-managed transaction

When an EJB container defines the boundaries of a transaction. An entity bean


must use container-managed transactions.

Context attribute

An object bound into the context associated with a servlet.

107
Glossary
==========================================================================================================================

Conversational state

The field values of a session bean plus the transitive closure of the objects
reachable from the bean's fields. The transitive closure of a bean is defined in
terms of the serialization protocol for the Java programming language, that is,
the fields that would be stored by serializing the bean instance.

Deployer

A person who installs modules and J2EE applications into an operational


environment.

Deployment

The process whereby software is installed into an operational environment.

Deployment descriptor

An XML file provided with each module and application that describes how they
should be deployed. The deployment descriptor directs a deployment tool to
deploy a module or application with specific container options and describes
specific configuration requirements that a deployer must resolve.

Deprecation

Refers to a class, interface, constructor, method or field that is no longer


recommended, and may cease to exist in a future version.

EJB container

A container that implements the EJB component contracts of the J2EE


architecture. This contract specifies a runtime environment for enterprise beans
that includes security, concurrency, life cycle management, transaction,
deployment, and other services. An EJB container is provided by an EJB or J2EE
server.

EJB Container Provider

A vendor that supplies an EJB container.

EJB context

An object that allows an enterprise bean to invoke services provided by the


container and to obtain the information about the caller of a client-invoked
method.

EJB home object

An object that provides the life cycle operations (create, remove, find) for an
enterprise bean. The class for the EJB home object is generated by the
container's deployment tools. The EJB home object implements the enterprise
bean's home interface. The client references an EJB home object to perform life
cycle operations on an EJB object. The client uses JNDI to locate an EJB home
object.

108
Glossary
==========================================================================================================================

EJB .jar file

A JAR archive that contains an EJB module.

EJB module

A software unit that consists of one or more enterprise beans and an EJB
deployment descriptor.

EJB object

An object whose class implements the enterprise bean's remote interface. A client
never references an enterprise bean instance directly; a client always references
an EJB object. The class of an EJB object is generated by the container's
deployment tools.

EJB server

Software that provides services to an EJB container. For example, an EJB


container typically relies on a transaction manager that is part of the EJB server
to perform the two-phase commit across all the participating resource managers.
The J2EE architecture assumes that an EJB container is hosted by an EJB server
from the same vendor so does not specify the contract between these two
entities. An EJB server may host one or more EJB containers.

EJB Server Provider

A vendor that supplies the EJB server.

EIS resource

An entity that provides EIS-specific functionality to its clients. Examples are: a


record or set of records in a database system, a business objects in an ERP
system, and a transaction program in a transaction processing system.

Enterprise Information System (EIS)

The applications that comprise an enterprise's existing system for handling


company-wide information. These applications provide an information
infrastructure for an enterprise. An EIS offers a well-defined set of services to its
clients. These services are exposed to clients as local and/or remote interfaces.
Examples of EISs include: an ERP system, a mainframe transaction processing
system, and a legacy database system.

Enterprise Bean Provider

An application programmer who produces enterprise bean classes, remote and


home interfaces, and deployment descriptor files, and packages them in an EJB
.jar file.

109
Glossary
==========================================================================================================================

Enterprise JavaBeans(TM) (EJB)

A component architecture for the development and deployment of object-


oriented, distributed, enterprise-level applications. Applications written using the
Enterprise JavaBeans architecture are scalable, transactional, and multi-user and
secure.

Entity bean

An enterprise bean that represents persistent data maintained in a database. An


entity bean can manage its own persistence or it can delegate this function to its
container. An entity bean is identified by a primary key. If the container in which
an entity bean is hosted crashes, the entity bean, its primary key, and any
remote references survive the crash.

HTTP

HyperText Transfer Protocol. The Internet protocol, based on TCP/IP, used to


fetch hypertext objects from remote hosts. See also

J2EE application

Any deployable unit of J2EE functionality. This can be a single module or a group
of modules packaged into an .ear file with a J2EE application deployment
descriptor. J2EE applications are typically engineered to be distributed across
multiple computing tiers.

J2EE product

An implementation that conforms to the J2EE platform specification.

J2EE Product Provider

A vendor that supplies a J2EE product.

J2EE server

The runtime portion of a J2EE product. A J2EE server provides Web and/or EJB
containers.

Java(TM) 2 Platform, Standard Edition (J2SE platform)

The core Java technology platform.

Java(TM) 2 Platform, Enterprise Edition (J2EE platform)

An environment for developing and deploying enterprise applications. The J2EE


platform consists of a set of services, application programming interfaces (APIs),
and protocols that provide the functionality for developing multi-tiered, Web-
based applications.

110
Glossary
==========================================================================================================================

Java(TM) 2 SDK, Enterprise Edition

Sun's implementation of the J2EE platform. This implementation provides an


operational definition of the J2EE platform.

JavaBeans(TM)

A portable, platform-independent reusable component model.

Java Database Connectivity (JDBC(TM))

An industry standard for database-independent connectivity between the


Java(TM) platform and a wide range of databases. The JDBC(TM) provides a call-
level API for SQL-based database access.

Java(TM) Message Service (JMS)

An API for using enterprise-messaging systems such as IBM MQ Series, TIBCO


Rendezvous, and so on.

Java Naming and Directory Interface(TM) (JNDI)

A set of APIs that assists with the interfacing to multiple naming and directory
services.

Java(TM) Remote Method Invocation (RMI)

A distributed object model for Java(TM) program to Java program, in which the
methods of remote objects written in the Java programming language can be
invoked from other Java virtual machines*, possibly on different hosts.

Java(TM) Runtime Environment (JRE)

A subset of the Java Development Kit (JDK(TM)) for end-users and developers
who want to redistribute the runtime environment alone. The Java runtime
environment consists of the Java virtual machine*, the Java core classes, and
supporting files.

JavaScript(TM)

A Web scripting language that is used in both browsers and Web servers. Like all
scripting languages, it is used primarily to tie other components together or to
accept user input.

JavaServer Pages(TM) (JSP)

An extensible Web technology that uses template data, custom elements,


scripting languages, and server-side Java objects to return dynamic content to a
client. Typically the template data is HTML or XML elements, and in many cases
the client is a Web browser.

111
Glossary
==========================================================================================================================

JSP action

A JSP element that can act on implicit objects and other server-side objects or
can define new scripting variables. Actions follow the XML syntax for elements
with a start tag, a body and an end tag; if the body is empty it can also use the
empty tag syntax. The tag must use a prefix.

JSP action, standard

An action that is defined in the JSP specification and is always available to a JSP
file without being imported.

JSP action, custom

An action described in a portable manner by a tag library descriptor and a


collection of Java classes and imported into a JSP page by a taglib directive.

JSP application

A stand-alone Web application written using the JavaServer Pages technology,


including JSP files, servlets, HTML files, images, applets, and JavaBeans
components.

JSP container

A container that provides the same services as a servlet container and an engine
that interprets and processes JSP pages into a servlet.

JSP container, distributed

A JSP container that can run a Web application that is tagged as distributable and
that executes across multiple Java virtual machines running on the same host or
on different hosts.

JSP declaration

A JSP scripting element that declares methods, variables, or both in a JSP file.

JSP directive

A JSP element that gives an instruction to the JSP container and is interpreted at
translation time.

JSP element

A portion of a JSP page that is recognized by a JSP translator. An element can be


a directive, an action, or a scripting element.

JSP expression

A scripting element that contains a valid scripting language expression that is


evaluated, converted to a String, and placed into the implicit out object.

112
Glossary
==========================================================================================================================

JSP file

A file named with a .jsp extension that a developer authors using standard HTML
tags, core JSP tags, custom JSP tags, and scripting language statements in order
to display dynamic pages in a Web browser.

JSP page

A text-based document using fixed template data and JSP elements that describe
how to process a request to create a response.

JSP scripting element

A JSP declaration, scriptlet, or expression, whose tag syntax is defined by the JSP
specification, and who’s content is written according to the scripting language
used in the JSP page. The JSP specification describes the syntax and semantics
for the case where the language page attribute is "java".

JSP scriptlet

A JSP scripting element containing any code fragment that is valid in the scripting
language used in the JSP page. The JSP specification describes what is a valid
scriptlet for the case where the language page attribute is "java".

JSP tag

A piece of text between a left angle bracket and a right angle bracket that is used
in a JSP file as part of a JSP element. The tag is distinguishable as markup, as
opposed to data, because it is surrounded by angle brackets.

JSP tag library

A collection of tags identifying custom actions described via a tag library


descriptor and Java classes. A portable Java class library that has a unique URI
and that defines custom tags that perform specialized tasks. A JSP tag library can
be imported into any JSP file and used with various scripting languages.

Java Web Server(TM)

The easy-to-use, extensible, easy-to-administer, secure, platform-independent


solution to speed and simplify the deployment and management of your Internet
and Intranet Web sites. It provides immediate productivity for robust, full-
featured, Java technology-based server applications.

JavaSoft(TM)

A former business unit of Sun Microsystems, Inc., currently known as Sun


Microsystems, Inc., Java Software division.

Passivation

The process of transferring an enterprise bean from memory to secondary


storage.

113
Glossary
==========================================================================================================================

Persistence

The protocol for transferring the state of an entity bean between its instance
variables and an underlying database.

Primary key

An object that uniquely identifies an entity bean within a home.

Servlet

A Java program that extends the functionality of a Web server, generating


dynamic content and interacting with Web clients using a request-response
paradigm.

Servlet container

A container that provides the network services over which requests and
responses are sent, decodes requests, and formats responses. All servlet
containers must support HTTP as a protocol for requests and responses, but may
also support additional request-response protocols such as HTTPS.

Servlet container, distributed

A servlet container that can run a Web application that is tagged as distributable
and that executes across multiple Java virtual machines running on the same
host or on different hosts.

Servlet context

An object that contains a servlet's view of the Web application within which the
servlet is running. Using the context, a servlet can log events, obtain URL
references to resources, and set and store attributes that other servlets in the
context can use.

Servlet mapping

Defines an association between a URL pattern and a servlet. The mapping is used
to map requests to servlets. If the container handling the request is a JSP
container, a URL containing a .jsp extension is implicitly mapped.

Session

An object used by a servlet to track a user's interaction with a Web application


across multiple HTTP requests.

Session bean

An enterprise bean that is created by a client and that usually exists only for the
duration of a single client/server session. A session bean performs operations,
such as calculations or accessing a database, for the client. While a session bean
may be transactional, it is not recoverable should a system crash occur. Session
bean objects can be either stateless or they can maintain conversational state
across methods and transactions. If they do maintain state, then the EJB

114
Glossary
==========================================================================================================================

container manages this state if the object must be removed from memory.
However, the session bean object itself must manage its own persistent data.

SGML

Standardized Generalized Markup Language. An ISO/ANSI/ECMA standard that


specifies a way to annotate text documents with information about types of
sections of a document.

Smart Web Services

Smart Web Services extend the basic concept of web services by adding the
dimension of user context, and are able to modify their operation to track along
with changes in a user's current situation. This includes the classic "who, what,
when, where, why" descriptors that come together to define a user's context at a
any given moment.

Stateful session bean

A session bean with a conversational state.

Stateless session bean

A session bean with no conversational state. All instances of a stateless session


bean are identical.

Thin Client

A system that runs a very light operating system with no local system
administration and executes applications delivered over the network.

URI

Uniform Resource Identifier. A compact string of characters for identifying an


abstract or physical resource. A URI is either a URL or a URN. URLs and URNs are
concrete entities that actually exist; A URI is an abstract superclass.

URL

Uniform Resource Locator. A standard for writing a text reference to an arbitrary


piece of data in the WWW. A URL looks like "protocol://host/localinfo" where
protocol specifies a protocol to use to fetch the object (like HTTP or FTP), host
specifies the Internet name of the host on which to find it, and localinfo is a string
(often a file name) passed to the protocol handler on the remote host.

URL path

The URL passed by a HTTP request to invoke a servlet. The URL consists of the
Context Path + Servlet Path + PathInfo, where Context Path is the path prefix
associated with a servlet context that this servlet is a part of. If this context is the
default context rooted at the base of the web server's URL namespace, the path
prefix will be an empty string. Otherwise, the path prefix starts with a / character
but does not end with a / character. Servlet Path is the path section that directly
corresponds to the mapping, which activated this request. This path starts with

115
Glossary
==========================================================================================================================

a / character. PathInfo is the part of the request path that is not part of the
Context Path or the Servlet Path.

Web application, distributable

A Web application that uses J2EE technology written so that it can be deployed in
a Web container distributed across multiple Java virtual machines running on the
same host or different hosts. The deployment descriptor for such an application
uses the distributable element.

Web component

A component that provides services in response to requests; either a servlet or a


JSP page.

Web container

A container that implements the Web component contracts of the J2EE


architecture. This contract specifies a runtime environment for Web components
that includes security, concurrency, life cycle management, transaction,
deployment, and other services. A container that provides the same services as a
JSP container and federated view of the J2EE platform APIs. A Web container is
provided by a Web or J2EE server.

XML

Extensible Markup Language. A markup language that allows you to define the
tags (markup) needed to identify the data and text in XML documents. J2EE
deployment descriptors are expressed in XML.

116
Glossary
==========================================================================================================================

Appendix

117
Appendix A
================================================================================================================================

Appendix A
Common HTTP Status Codes

OK 200
The request was fulfilled.

Bad request 400


The request had bad syntax or was inherently impossible to be satisfied.

Unauthorized 401
The parameter to this message gives a specification of authorization schemes which
are acceptable. The client should retry the request with a suitable Authorization
header.

PaymentRequired 402
The parameter to this message gives a specification of charging schemes acceptable.
The client may retry the request with a suitable ChargeTo header.

Forbidden 403
The request is for something forbidden. Authorization will not help.

Not found 404


The server has not found anything matching the URI given

Internal Error 500


The server encountered an unexpected condition which prevented it from fulfilling
the request.

Not implemented 501


The server does not support the facility required.

Service temporarily overloaded 502


The server cannot process the request due to a high load (whether HTTP servicing or
other requests). The implication is that this is a temporary condition which maybe
alleviated at other times.

Gateway timeout 503 (TO BE DISCUSSED)


This is equivalent to Internal Error 500, but in the case of a server which is in turn
accessing some other service, this indicates that the response from the other service
did not return within a time that the gateway was prepared to wait. As from the
point of view of the client and the HTTP transaction the other service is hidden within
the server, this maybe treated identically to Internal error 500, but has more
diagnostic value.

118
Appendix B
================================================================================================================================

Appendix B
FAQ

Q: What is a output comment?

A: A comment that is sent to the client in the viewable page source. The JSP engine
handles an output comment as uninterpreted HTML text, returning the comment in
the HTML output sent to the client. You can see the comment by viewing the page
source from your Web browser.

JSP Syntax
<!-- comment [ <%= expression %> ] -->

Example 1
<!-- This is a comment sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:


<!-- This is a comment sent to client on January 24, 2004 -->

Q: What is a Hidden Comment?

A: A comments that documents the JSP page but is not sent to the client. The JSP
engine ignores a hidden comment, and does not process any code within hidden
comment tags. A hidden comment is not sent to the client, either in the displayed
JSP page or the HTML page source. The hidden comment is useful when you want to
hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%>
combination. If you need to use --%> in your comment, you can escape it by typing
--%\>.
JSP Syntax
<%-- comment --%>

Q: What are implicit objects? List them?

A: Certain objects that are available for the use in JSP documents without being
declared first. These objects are parsed by the JSP engine and inserted into the
generated servlet. The implicit objects re listed below
request
response
pageContext
session
application
out
config
page
exception

119
Appendix B
================================================================================================================================

Q: Difference between forward and sendRedirect?

A: When you invoke a forward request, the request is sent to another resource on
the server, without the client being informed that a different resource is going to
process the request. This process occurs completely with in the web container. When
a sendRedirect method is invoked, it causes the web container to return to the
browser indicating that a new URL should be requested. Because the browser issues
a completely new request any object that are stored as request attributes before the
redirect occurs will be lost. This extra round trip a redirect is slower than forward.

Q: Explain the life-cycle methods in JSP?

A: The generated servlet class for a JSP page implements the HttpJspPage interface
of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage
interface which intern extends the Servlet interface of the javax.servlet package. the
generated servlet class thus implements all the methods of the these three
interfaces. The JspPage interface declares only two methods - spinet() and
jspDestroy() that must be implemented by all JSP pages regardless of the client-
server protocol. However the JSP specification has provided the HttpJspPage
interface specifically for the JSP pages serving HTTP requests. This interface declares
one method _jspService().
The jspInit()- The container calls the jspInit() to initialize the servlet instance. It is
called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it
the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of
service. It is the last method called n the servlet instance.

Q: What is the difference between the getRequestDispatcher(String path)


method of javax.servlet.ServletRequest interface and
javax.servlet.ServletContext interface?

A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest


interface accepts parameter the path to the resource to be included or forwarded to,
which can be relative to the request of the calling servlet. If the path begins with a
"/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext


interface cannot accepts relative paths. All path must start with a "/" and are
interpreted as relative to current context root.

Q: Explain the directory structure of a web application.

A: The directory structure of a web application consists of two parts.


A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of


1. web.xml
2. classes directory

120
Appendix B
================================================================================================================================

3. lib directory

Q: Explain ServletContext.

A: ServletContext interface is a window for a servlet to view it's environment. A


servlet can use this interface to get information such as initialization parameters for
the web application or servlet container's version. Every web application has one and
only one ServletContext and is accessible to all active resource of that application.

Q: What is preinitialization of a servlet?

A: A container doesn’t initialize the servlets ass soon as it starts up, it initializes a
servlet when it receives a request for that servlet first time. This is called lazy
loading. The servlet specification defines the <load-on-startup> element, which can
be specified in the deployment descriptor to make the servlet container load and
initialize the servlet as soon as it starts up. The process of loading a servlet before
any request comes in is called preloading or preinitializing a servlet.

Q: What is the difference between Difference between doGet() and


doPost()?

A: A doGet() method is limited with 2k of data to be sent, and doPost() method


doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call
doesn't need a long text tail after a servlet name in a request. All parameters are
stored in a request itself, not in a request string, and it's impossible to guess the
data transmitted to a servlet only looking at a request string.

Q: What is the difference between HttpServlet and GenericServlet?

A: A GenericServlet has a service() method aimed to handle requests. HttpServlet


extends GenericServlet and adds support for doGet(), doPost(), doHead() methods
(HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

121
Appendix C
================================================================================================================================

Appendix C

MVC Architecture

1.What are Design Patterns?

As you design and build different applications, you continually come across the same
or very similar problem domains. This leads you to find a new solution for the similar
problem each time. To save time and effort, it would be ideal if there was a
repository which captured such common problem domains and proven solutions.

In the simplest term, such a common solution is a design pattern. The repository
or place of reference that contains these patterns is a design pattern catalog.

A design pattern describes a proven solution, from experienced hands, for a


recurring design problem. These solutions are very generic. They are described in
well-defined Pattern Templates, with the most popular template defined by the Gang
of Four.

The pattern template usually includes a name that gives an idea as to what that
pattern is about, followed by where the pattern is applicable, the motivation, the
issues in implementation, and so on. Apart from describing the problem and
illustrating the solution, the pattern also explains the implementation issues involved
and consequences, if any, of using the pattern.

Use of such patterns makes the design of an application transparent. These patterns
have been used successfully by developers in their respective fields, and therefore,
the pros and cons of the pattern (as well as implementation issues) are known
beforehand. All design patterns are reusable and can be adapted to particular
contexts. This gives you flexibility. The use of design patterns related to J2EE
applications gives the added advantage of showing solutions in terms of J2EE
platform technologies.

2.Design Patterns For Building Flexible and Maintainable J2EE Applications

Multi-tiered J2EE applications consist of a number different views and components in


the middle tier, possibly distributed. The following sections of this article suggest
some design patterns that can help you keep typical J2EE applications extensible,
flexible, and maintainable. Instead of discussing some abstract scenarios, this
articles takes an imaginary sample application and tries to give you an
understanding of these patterns in the context of this sample application. Once you
know the sample application it is easier to extend the use of these patterns to other
application scenarios.

Take the case of an enterprise application for financial services over the web. Visitors
to this site can browse through the list of services, create accounts, place orders for
the products made available by the financial service, and so on. Also assume that
this application allows existing customers to change their account details and profile,
make use of services, and so on. Typically this kind of application has multiple views

122
Appendix C
================================================================================================================================

or screens which users click through to search for lists of services, access profiles,
use the services, and to get other information. The business logic represents the
user's account, profile, the catalog of services, ordering for services, and so on, as
separate entities in the form of Enterprise JavaBeans (EJB). With this sample
application in mind, look at some recurring problems and see how you can use
specific patterns to build a flexible and maintainable application.

3.Model-View-Controller

Problem Domain

All would be well if you were building this enterprise application for a single type of
client. If that were the case, we could simply mix the data access / data modifying
logic with the logic for the various client views. But with the advent of the completely
interconnected and wireless world, there are client devices ranging from PDAs to cell
phones to a browser on a powerful desktop, in addition to other types of traditional
clients. In this scenario, solving this problem by mixing data access with views is
problematic because

• You must develop different versions of the same application to suit each type
of client needs support
• Since the code for views and that for data access/modification is intertwined,
the code for the data access/modification is duplicated everywhere, thereby
making the application almost unmaintainable
• The development life cycle is extended unnecessarily.

Suggested Solution

In finding a solution for this problem, take note that:

• Regardless of the client type, the data being accessed and displayed comes
from the same enterprise data source.
• All clients must be able to modify the data source.
• Modifying either a type of client or data accessing / modifying logic should
not affect the other components of the application.

You need a solution that lets you develop loosely-coupled applications. The Model-
View-Controller (MVC) architecture is the suggested solution. MVC has been used
very effectively in GUI-type applications. By applying the MVC architecture to a J2EE
application, you can separate the data access logic from the data presentation logic.
You can also build a flexible and easily extensible controller that controls the whole
flow of the application. The figure below depicts the MVC architecture.

123
Appendix C
================================================================================================================================

The MVC architecture can be mapped to multi-tiered enterprise J2EE applications as


follows:

• All enterprise data and the business logic to process the data can be
represented in the MODEL.
• The VIEW can access the data through the model and decide on how to
present them to the client. The VIEW must ensure that the presentation changes
as and when the MODEL changes.
• The CONTROLLER can interact with the view and convert the client actions
into actions that are understood and performed by the MODEL. The CONTROLLER
also decides on the next view to be presented depending on the last client action
and results of the corresponding MODEL action(s).

Applying the above logic to the sample financial application, you build the application
as follows:

• The business logic of the application is represented by EJBs that form the
MODEL of MVC architecture. The MODEL responds to requests from CONTROLLER
to access / modify the data it represents.
• The various screens of the application forms the VIEW of the MVC
architecture. The VIEW updates itself when the MODEL changes.
• The CONTROLLER of the application is a set of objects that receive the user
actions, convert them into requests understood by the model, and decide on the
next screen to be displayed once the model completes the processing request

It is very difficult to fully showcase the MVC architecture in the form of a small
example code. The Java Pet Store Demo application from the J2EE BluePrints
Program is a good example of a complete J2EE application that is based on the MVC
architecture.

124
Appendix C
================================================================================================================================

Points to Note

Here are some points to note:

• MVC architecture is suitable for a highly interactive system that requires


extensibility, maintainability, and multiple user views.
• MVC decouples presentation, user interaction, and system model.
• Presenting multiple views for multiple data sets is made easy because of the
decoupling. This also makes it much easier to enable support for new types of
clients.
• Code duplication is minimized by using this architecture.
• By separating the presentation from model and overall application flow, this
architecture enables division of developer responsibilities, and thereby, produces
faster time to market.

125
Reference
================================================================================================================================

References

Book References:

Title Author Publication Edition


Professional Java
Subramanyam
Server APress J2EE 1.3 Edition
Allamaraju
Programming
Expert One-on-One
Wiley Publishing
J2EE Design and Rod Johnson 2003
Inc.
Development
Core J2EE Patterns:
Deepak Alur, Dan
Best Practices and Sun Press Second Edition
Malks, John Crupi
Design Strategies
Richard Monson-
Enterprise
Haefel, Bill Burke, O’Reilly Fourth Edtion
JavaBeans
Sacha Labourey
Bryan Basham,
Head First Servlets
Kathy Sierra , Bert O’Reilly 2004
& JSP
Bates

Online References:

URL Description
The J2EE home website, containing the
http://java.sun.com most current information on the J2EE
Platform
http://java.sun.com/j2ee/docs.html The complete J2EE API.
www.experts-exchange.com J2EE Interview questions.
http://bea.com Weblogic Home Website
www.ejbtut.com EJB Tutorial

126
Reference
================================================================================================================================

Lab Works

127
Reference
================================================================================================================================

Servlet & JSP Programs

Servlet

1. JDBC:
import java.lang.*;
import javax.sql.*;
import java.sql.*;

class db1
{
public static void main(String args[]) throws Exception
{
int no;
String name,place;

Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver has loaded");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/prem
","root","admin");
System.out.println("Connection Established");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp1");

System.out.println("\t\t NO \t\t NAME \t\t PLACE");

while(rs.next())
{
no=rs.getInt(1);
name=rs.getString(2);
place=rs.getString(3);
System.out.println("\t\t "+no+"\t\t "+name+"\t\t "+place);
}
}
}

2.Simple Servlet Program:

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

public class servlet1 extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
out.println("***WELCOME***");

128
Reference
================================================================================================================================

}
catch(Exception e){}
}
}

3.JDBC & Servlets:

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

public class servlet3 extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
try
{
int no;
String name,place;
PrintWriter out=res.getWriter();
res.setContentType("text/html");
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:330
6/prem","root","admin");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp1");
out.println("CONTENTS IN THE TABLE<br>");
out.println("NO NAME PLACE<br>");

while(rs.next())
{
no=rs.getInt(1);
out.println(no);
name=rs.getString(2);
out.println(name);
place=rs.getString(3);
out.println(place);
out.println("<br>");
}
}
catch(Exception e){}
}
}

129
Reference
================================================================================================================================

4. Simple login page:

login.html:
<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>

<form action="login" method="get">


USERNAME <input type="text" name="usname"><br><br>
PASSWORD <input type="password" name="psword"><br><br>

<input type="submit" value="Submit">


<input type="reset" value="Reset">
</form>
</BODY>
</HTML>

login.java:

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

public class login extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
String s1=req.getParameter("usname");
String s2=req.getParameter("psword");
out.println("Welcome to Home Page <br>");
out.println("Ur user name is : "+s1);
}
catch(Exception e){}
}
}

5.Session:

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

public class sessioncount extends HttpServlet


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

130
Reference
================================================================================================================================

try
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession(true);
if(hs.getAttribute("counter")==null)
{
hs.setAttribute("counter", new Integer(1));
}
else
{
int c=((Integer) hs.getAttribute("counter")).intValue()+1;
hs.setAttribute("counter", new Integer(c));
}
pw.println("<h1> USER VIEWERS : " +hs.getAttribute("counter"));
}
catch(Exception e) {}
}
}

6.Cookies:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class cookies extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
try
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
Cookie c1=new Cookie("Emp no","001");
Cookie c2=new Cookie("Emp name","prem");
Cookie c3=new Cookie("User id","pp");

c1.setMaxAge(1000);
c2.setMaxAge(1000);
c3.setMaxAge(1000);

res.addCookie(c1);
res.addCookie(c2);
res.addCookie(c3);

pw.println("<h2> Response sets all the cookies");


}
catch (Exception e) {}
}
}

131
Reference
================================================================================================================================

7. Servlet Inter-Communication (Request Dispatcher):

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

public class servletcomm_rd extends HttpServlet


{
RequestDispatcher rd;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter p=res.getWriter();
String name=req.getParameter("name");
String psword=req.getParameter("psword");

if(name.equals("prem")==false)
{
rd=req.getRequestDispatcher("/invalid");
rd.forward(req,res);
}
else
{
rd=req.getRequestDispatcher("/valid");
rd.forward(req,res);
}
}
}

8. Servlet Inter-Communication (Send Redirect):

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

public class servletcomm_srd extends HttpServlet


{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter p=res.getWriter();
String name=req.getParameter("name");
String psword=req.getParameter("psword");

if(name.equals("prem")==false)
{
res.sendRedirect("http://127.0.0.1:7001/Servlets/invalid");
}
else

132
Reference
================================================================================================================================

{
res.sendRedirect("http://127.0.0.1:7001/Servlets/valid");
}
})
JSP

9. JSP Directive:

<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<%@ page import="java.util.Date" %>
<%@ include file="included.html"%>
Current date is <%= new Date() %>
</BODY>
</HTML>

10. Jsp Scripting:

<HTML>
<%
int c=3;

public String disp(String s)


{
return "WELCOME " + s + "..!!";
}
%>
<BODY>
<h1><CENTER> METHOD DECLERATION </CENTER></H1>
<p> The value of count is : <%=c %></p>
<p> HELLO <%= disp("FRIENDS") %></p>
</BODY>
</HTML>

11. Jsp & Servlets:

login.jsp:

<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>

<form action="login" method="get">


USERNAME <input type="text" name="usname"><br><br>
PASSWORD <input type="password" name="psword"><br><br>

<input type="submit" value="Submit">


<input type="reset" value="Reset">
</form>

133
Reference
================================================================================================================================

</BODY>
</HTML>

login.java:

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

public class login extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
String s1=req.getParameter("usname");
String s2=req.getParameter("psword");
out.println("Welcome to Home Page <br>");
out.println("Ur user name is : "+s1);
}
catch(Exception e){}
}
}

12. Jsp, Servlets & JDBC:

login.jsp:

<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>

<form action="login" method="get">


USERNAME <input type="text" name="name"><br><br>
PASSWORD <input type="password" name="psword"><br><br>

<input type="submit" name="submit">


<input type="reset" name="reset">
</form>
</BODY>
</HTML>

loginservlet.java:

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

134
Reference
================================================================================================================================

public class loginservlet extends HttpServlet


{
RequestDispatcher rd;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/prem
","root","admin");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from login");

String name1,psword;
int c=0;
res.setContentType("text/plain");
PrintWriter p=res.getWriter();
String n=req.getParameter("name");
String pw=req.getParameter("pass");
HttpSession hs=req.getSession();

while(rs.next())
{
name1=rs.getString(1);
psword=rs.getString(2);
if(n.equals(name1))
if(pw.equals(psword))
{
hs.setAttribute("n",name1);
hs.setAttribute("pw",psword);
rd=req.getRequestDispatcher("/valid.jsp");
rd.forward(req,res);
c++;
}
}
if(c==0)
{
rd=req.getRequestDispatcher("/invalid.jsp");
rd.forward(req,res);
}
}
catch(Exception e) {}
}
}

135
Reference
================================================================================================================================

valid.jsp:
<html>
<body>

<%@page language="java" %>

<%
String name=(String) session.getAttribute("n");
out.println(" <h1><b><center> WELCOME !!
</h1></b></center><br></br>");
out.println(" <h3><i> USER NAME IS : " + name+ "</h3></i>");
%>

</body>
</html>

invalid.jsp:
<html>
<body>

<%@page language="java" %>

<%
out.println("YOU ARE NOT A VALID USER");
%>

</body>
</html>

136
Notes
================================================================================================================================

137
Notes
================================================================================================================================

138
Notes
================================================================================================================================

139

You might also like