Professional Documents
Culture Documents
===========================================================================================================================
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
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.
1
J2EE Servlets & JSP
===========================================================================================================================
What makes J2EE credible as a platform
First however, let us start with the challenges of developing applications for 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.
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.
3
J2EE Servlets & JSP
===========================================================================================================================
Application
DB
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.
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.
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.
5
J2EE Servlets & JSP
===========================================================================================================================
Browser
Firewall
Application Client
Presentation Logic
Business Logic
Service
XML
Document
DB s
6
J2EE Servlets & JSP
===========================================================================================================================
Database Middleware
XML
Remote Systems DB Document
s
7
J2EE Servlets & JSP
===========================================================================================================================
1.4.2 Reusability
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.
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 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
===========================================================================================================================
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.
RMI/IIOP,JNDI,JTA, RMI/IIOP,JNDI,JTA,
JDBC,JMS,javaMail, JDBC,JMS,javaMail,
JAF JAF
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.
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.
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
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.
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.
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.
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
===========================================================================================================================
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
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.
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.
13
J2EE Servlets & JSP
===========================================================================================================================
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.
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 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
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:
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>
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:
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 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
• 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 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 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 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
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.).
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.
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.*;
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
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.
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 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:
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>");
}
}
<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.
26
J2EE Servlets & JSP
===========================================================================================================================
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.
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.
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.
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.*;
<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
Topics Discussed
Servlet Collaboration
Servlet Chaining
Request Dispatching
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:
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.
30
J2EE Servlets & JSP
===========================================================================================================================
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.
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.
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.
• RequestDispatcher Interface
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.
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.
This method lets you include the content produced by another resource in the
calling servlet’s response.
There are three ways in which you can obtain a RequestDispatcher object for a
resource:
32
J2EE Servlets & JSP
===========================================================================================================================
javax.servlet.ServletRequest method getRequestDispatcher():
Although these methods serve the same purpose, the usage depends on what
information is available to you.
container can use this to resolve relative paths into absolute paths.
Note that the target resource (except for static resources) should implement the
same type of HTTP request that the original servlet receives.
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:
<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>
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
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
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.)
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:
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.
<%@page import=”java.util.Date”%>
<html>
<body>
The current time is <%=new Date(), toString() %>
</body>
</html>
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.
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.
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):
or:
38
J2EE Servlets & JSP
===========================================================================================================================
Any whitespace within the body text of a document is not significant,
but is preserved during translation into a servlet.
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.)
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:
where the valid attributes are name value pairs as described overleaf:
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.
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.
Example
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).
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:
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.
<html>
<head>
<title>Include directive test page 1</title>
</head>
<body>
<h1>Include directive test page 1</h1>
<%@ include file="included.html"%>
</body>
</html>
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>
43
J2EE Servlets & JSP
===========================================================================================================================
You can see that the code from the included file has been inlined into the
translated servlet.
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:
Tag libraries are a very powerful, and often misunderstood, concept, and
will be covered in detail in coming Chapters.
5.4.1 Declarations
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:
Example
<%!
int numTimes = 3;
<html>
<head>
<title>Declaration test page </title>
</head>
<body>
<h1>Declaration test page</h1>
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.
import javax.servlet.*;
// … more import statements
45
J2EE Servlets & JSP
===========================================================================================================================
public class 0002fdeclaration0002ejspdeclaration_jsp_1
extends HttpJspBase (
int numTimes = 3;
5.4.2 Scriptlets
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:
Example
<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>
46
J2EE Servlets & JSP
===========================================================================================================================
5.4.3 Expressions
Example
<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.
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.
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
class=”className”
class=”className” type=”typeName”
beanName=”beanName” type=”typeName”
type=”typeName”
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.
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.
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.
5.5.2 jsp:setProperty
When setting bean properties from the request object, the JSP can choose to set
all properties in the bean via the standard action:
property=”*”
property=”propertyName”
property=”propertyName” param=”parameterName”
property=”propertyName” value=”propertyValue”
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.
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
52
J2EE Servlets & JSP
===========================================================================================================================
The syntax is:
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.
<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>
</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.
package bean1;
public class LanguageBean
{
private String name;
private String language;
private String languageComments;
public LanguageBean(){}
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.
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:
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
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.
or:
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.
It is important to understand the difference between the include directive and this
include action; the difference is summarized in the table below:
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.
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>
and include2.jsp:
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.
// …
//…
}
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>
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.
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>
</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"))) {
%>
<% } %>
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.
<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>
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:
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
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 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 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 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 represents the servlet context, obtained from the servlet
configuration object. It is of type javax.servlet.ServletContext and has application
scope.
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 is the ServletConfig for this JSP page, and has page scope. It is
of type javax.servlet.ServletConfig.
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
What happens when a bean tag is compiled for the different values of scope can
be seen below:
Page Scope
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.
This is the default scope for objects used with the <jsp:useBean> action.
Request Scope
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
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
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
Topics Discussed
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:
Let’s get started then with what tag extensions are all about.
66
J2EE Servlets & JSP
===========================================================================================================================
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:
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:
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.
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
===========================================================================================================================
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).
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.
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:
Before we return to our simple example, let’s cover some basic theory of 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.
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.
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.
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.
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:
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.)
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.
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 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.
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.
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.
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.
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:
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( ).
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:
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.
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:
73
J2EE Servlets & JSP
===========================================================================================================================
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.
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.
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.
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.*;
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.)
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.
<!ELEMENT taglib
(tlibversion, jspversion?,
shortname, uri?, info?,
tag+) >
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.
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.
<!ELEMENT attribute
(name, required?, rtexprevalue?) >
name is the name of this attribute, as it will appear in JSPs using the tag.
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()%>’>
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:
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.
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:
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.
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:
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:
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?>
<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>
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
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.
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.
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
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
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
84
J2EE Servlets & JSP
===========================================================================================================================
• DBMS The database management system, that deals with the actual storage
and retrieval of data.
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.
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.
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.
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.
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.
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.
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.
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);
DriverManager.registerDriver (this);
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 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.
where the question mark symbol(?) is the placeholder for the parameters/
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.
setType Methods
91
J2EE Servlets & JSP
===========================================================================================================================
void setByte(int index, byte b) Byte TINYINT
getType Methods
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.
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:
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.
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
Proprietary
Protocol
Library
Database
Fig. 7.6
The Native library-to-Java 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
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
Fig. 7.8
95
J2EE Servlets & JSP
===========================================================================================================================
The Native Protocol 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.
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.
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.
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");
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.
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(?, ?)");
System.out.println("value inserted");
}
}
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.
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 5: In the command promptness pass the empno. You will get the
corresponding deptno
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.
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
===========================================================================================================================
}
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);
}
}
}
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
Application client
A first-tier client program that executes in its own Java Virtual Machine.
A container that supports application clients and provides a federated view of the
J2EE platform APIs.
A software unit that consists of one or more classes and an application client
deployment descriptor.
A vendor that provides the Java classes that implement components' methods,
JSP page definitions, and any required deployment descriptors.
APM
Atomic
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
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
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
Bean-managed transaction
Business logic
Business method
Callback methods
Classpath
Client
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
Commit
The point in a transaction when all updates to any resources involved in the
transaction are made permanent.
Component
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
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
Context attribute
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
Deployment
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
EJB container
EJB context
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 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
EIS resource
109
Glossary
==========================================================================================================================
Entity bean
HTTP
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
J2EE server
The runtime portion of a J2EE product. A J2EE server provides Web and/or EJB
containers.
110
Glossary
==========================================================================================================================
JavaBeans(TM)
A set of APIs that assists with the interfacing to multiple naming and directory
services.
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.
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.
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.
An action that is defined in the JSP specification and is always available to a JSP
file without being imported.
JSP application
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.
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
JSP expression
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.
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.
JavaSoft(TM)
Passivation
113
Glossary
==========================================================================================================================
Persistence
The protocol for transferring the state of an entity bean between its instance
variables and an underlying database.
Primary key
Servlet
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.
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
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
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.
Thin Client
A system that runs a very light operating system with no local system
administration and executes applications delivered over the network.
URI
URL
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.
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
Web container
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.
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.
118
Appendix B
================================================================================================================================
Appendix B
FAQ
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() %>
-->
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 --%>
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
================================================================================================================================
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.
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.
120
Appendix B
================================================================================================================================
3. lib directory
Q: Explain ServletContext.
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.
121
Appendix C
================================================================================================================================
Appendix C
MVC Architecture
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.
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.
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
• 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
================================================================================================================================
• 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
125
Reference
================================================================================================================================
References
Book References:
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
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");
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);
}
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
128
Reference
================================================================================================================================
}
catch(Exception e){}
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
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
================================================================================================================================
login.html:
<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>
login.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
5.Session:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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.*;
c1.setMaxAge(1000);
c2.setMaxAge(1000);
c3.setMaxAge(1000);
res.addCookie(c1);
res.addCookie(c2);
res.addCookie(c3);
131
Reference
================================================================================================================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
if(name.equals("prem")==false)
{
rd=req.getRequestDispatcher("/invalid");
rd.forward(req,res);
}
else
{
rd=req.getRequestDispatcher("/valid");
rd.forward(req,res);
}
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.lang.*;
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>
<HTML>
<%
int c=3;
login.jsp:
<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>
133
Reference
================================================================================================================================
</BODY>
</HTML>
login.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
login.jsp:
<HTML>
<HEAD>
<TITLE> USER LOGIN </TITLE>
<BODY>
loginservlet.java:
import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
134
Reference
================================================================================================================================
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>
<%
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>
<%
out.println("YOU ARE NOT A VALID USER");
%>
</body>
</html>
136
Notes
================================================================================================================================
137
Notes
================================================================================================================================
138
Notes
================================================================================================================================
139