Transaction

advertisement
SEN 974 Enterprise and Web
Application Programming
Transaction Management
Web Tier - Java Server Pages
(JSP)
1
Topics

Transaction management concepts


Basic concepts
The Web Tier


Servlets
Java Server Pages (JSP)
2
Introducing Transactions

Transactions


A group of processes that either all succeed or all fail
Transaction Management (TM)



Mechanism for simplifying the development of distributed multi-user
enterprise applications
Standard service offered by J2EE platform
By enforcing strict rules on a application’s ability to access and update
data, transaction management ensures data integrity


Frees the programmer from dealing with the complex issues of:





Means that TM ensures that a unit of work either fully completes or has no
effect at all.
data access
synchronized failures
failure recovery, and
multi-user programming
Example – ATM for a bank
3
If error occurs before – no harm done
What happens if network goes
down here?
The ACID Test

Use the mnemonic “ACID” to remember these
characteristics:

Atomicity



All of the distinct actions appear to be as a single atom—
an unbreakable whole. Or, the “all succeed or all fail”
notion
If any operation in the transaction fails – the transaction
fails
Consistency



A transaction must transition data from one consistent
sate to another, preserving the data’s semantic and
referential integrity
System is in a stable state before the transaction as well
as after.
Any temporary work or any transitory values are cleared
away by the end of the transaction.
5
The ACID Test

Isolation



Means that any changes made to data by a transaction are
invisible to other concurrent transactions until the
transactions commits.
Requires that several concurrent transactions must product
the same results in the data as those same transactions
executed serially
In reality, a system (whether it be an application server or
a database) will be answering multiple requests in parallel,
but they should be able to be serialized, which is to be
performed one-at-a-time, as if they had queued up rather
than assaulting the server all at once. The theory behind
this is that if the same transactions are fed to the server in
the same order, it should reach the same ending state.
6
The ACID Test

Durability



Committed changes are permanent
Failures that occur after a commit cause no loss
of data
Implies that data for all committed transactions
can be recovered after a system or media failure
7
Transaction Participants



An application that uses transactions is called a transactional application.
In a J2EE application, a transactional application may consist of multiple
servlets, JSP pages, and enterprise beans.
A resource manager is an external system accessed by an application.


A resource manager provides and enforces the ACID transaction properties for
specific data and operations.
Examples of resource managers include a




relational database (which support persistent storage of relational data),
an EIS system (managing transactional, external functionality and data), and the
JavaMessage Service (JMS) provider (which manages transactional message
delivery).
A transactional application accesses a resource manager through a
transactional resource object.



For example, a JDBC java.sql.Connection object is used to access a relational
database.
A resource adapter is a system library that makes the API of a resource
manager available to an application server.
A Connector is a resource adapter that has an API conforming to the Java
Connector architecture, the standard architecture for integrating J2EE
applications with EISes.
8
Transaction Demarcation








Transactional programs must be able to start and end
transactions, and be able to indicate whether data changes are to
be made permanent or discarded.
Indicating transaction boundaries for a program is called
transaction demarcation.
A program starts a transaction by executing a begin operation.
The program may then read or modify data within the scope of
the new active transaction.
When the program is ready to make its data changes permanent,
it executes a commit operation, causing the transaction to persist
any data modified or created during the active state.
Successful completion of the commit operation results in a
permanent change to the transactional resource.
If a commit operation fails (for example, due to inadequate
resources or data consistency violations), the resource manager
executes a rollback, discarding any changes made since the
transaction began.
An application may also explicitly request a rollback during an
9
active transaction.
Distributed Transactions






Distributed enterprise systems often need to access and update
multiple transactional resources in order to accomplish some
business goal.
Distributed transactions are more complex than non-distributed
transactions because of latency, potential failure of one or more
resource managers, and interoperability concerns.
On a network, a failed transaction can be difficult to distinguish
from one that is merely slow. Resource managers that do not
“know” about each other cannot coordinate transactions by
themselves.
A transactional application could itself handle rollbacks and
commits for multiple distributed resources, but only at the cost of
a great deal of complex, non-reusable logic.
A transaction context is the association of a transaction with an
application component or a resource manager.
The transparent forwarding of a transaction context from one
component to another component or from a component to a
resource manager is called transaction context propagation.
10
Transaction Manager



The most common solution to the problem of
coordinating distributed transactions is to
introduce a third participant, called a
transaction manager, into the design.
The transaction manager acts as a mediator
between applications and the multiple
resources the applications use.
At any time during a distributed transaction,
the transaction manager maintains an
association between each transaction (which
has a unique global ID), application threads,
and connections to the resource managers.
11
Distributed Transaction
Participants
12
Locking and Shadow Pages




The usual solution to simultaneous access to shared resources is
to employ a locking device, called a lock in a database or a
mutex in the operating system.
A lock is a method of ensuring that only one process has
exclusive privileges to change the state of a resource at a time.
Should multiple requests require access to the same resource
(such as a record of a customer’s bank account), then only one is
allowed to access the resource at a time.
ATM example from before:



When the verification of the account takes place, a lock is placed
upon that particular row to ensure that it remains exactly as it is until
the transaction is complete.
If at this time, the customer account was to be deleted, it would
either fail or have to wait as the ATM’s process would have acquired
a lock upon the customer’s account.
This wait would ensure that when the account is closed, the
customer would receive only what is left in her account.
13
Locking




The basic problem is that a lock is required for
both writing and reading any particular
resource (Consistency).
If a second process were to read a row from a
database while it was in use (i.e. being
modified), it might not receive an accurate
value.
For lengthy transactions, any other processes
might have to wait just to read a single value.
Locking issue – does not scale well.
14
Shadow Pages





In effect, the database makes a copy of data
that is undergoing change
One copy of the data is the pre-transaction
copy (i.e. original value).
One copy is undergoing change.
All read requests are forwarded to the pretransaction copy, ignorant of any changes that
are underway.
Should a second process decided to make its
own changes, it will still be blocked by the lock
on that data and have to wait.
15
Two Phase Commit Protocol




Resource managers that do not “know” about one
another can’t cooperate directly in distributed
transactions
So Transaction manager controls the transaction,
indicating to each resource manager whether and
when to commit or roll back, based on the global state
of the transaction.
A transaction manager coordinates transactions
between resource managers using a two-phase
commit protocol.
The two-phase commit protocol provides the ACID
properties of transactions across multiple resources.
17
Two Phase Commit Protocol



In the first phase of two-phase commit, the
transaction manager tells each resource to
“prepare” to commit - to perform all operations
for a commit and be ready either to make the
changes permanent or to undo all changes.
Each resource manager responds, indicating
whether or not the prepare operation
succeeded.
In the second phase, if all prepare operations
succeed, the transaction manager tells all
resource managers to commit their changes;
otherwise, it tells them all to roll back and
indicates transaction failure to the application.18
J2EE Platform Transactions



The J2EE platform supports a
combination of servlets and JSP pages
accessing multiple enterprise beans
within a single transaction.
Each component may acquire multiple
connections to multiple resource
managers.
The J2EE platform supports both
programmatic and declarative transaction
demarcation.
19
J2EE Transaction Management



J2EE Transaction Management is transparent
to component and application code.
A J2EE application server implements the
necessary low-level transaction protocols, such
as interactions between a transaction manager
and resource managers, and distributed twophase commit protocol.
The J2EE platform requires only support for
so-called “flat” transactions, which cannot have
any child (nested) transactions.
20
Example: Transactions across
Multiple Resource Managers

The following scenario illustrates a J2EE transaction
that spans multiple resource managers:
Transaction -->
21
Example: Transactions across
Multiple Resource Managers






Client invokes a method on enterprise bean X.
Bean X accesses database A using a JDBC connection.
Then enterprise bean X calls a method on another
enterprise bean Y, which sends a JMS message to some
other system using a JMS provider.
Enterprise bean Y then invokes a method on enterprise
bean Z, which updates and returns some data from an
external EIS system using a resource adapter that
implements the J2EE Connector architecture.
The transaction manager in the J2EE server coordinates
activities with the three resource managers.
The server ensures that the database update by bean X,
the message transmission by bean Y, and the EIS operation
performed by bean Z are either all committed, or all rolled
back.
22
Example: Transactions across
J2EE Servers

J2EE products can distribute transactions
across multiple application servers:
23
Example: Transactions across
J2EE Servers



Client invokes enterprise bean X, which updates data
in enterprise information system A, and then calls
another enterprise bean Y that is hosted by a different
J2EE server.
Enterprise bean Y performs read-write access to
enterprise information system B.
When X invokes Y, the two J2EE servers cooperate to
propagate the transaction context from X to Y.


This transaction context propagation is transparent to the
application code.
At transaction commit time, the two J2EE servers use
a distributed two-phase commit protocol to ensure that
the two enterprise information systems are updated
within a single transaction.
24
J2EE Transaction Technologies



The Java Transaction API and the J2EE
platform specifications define the overall
transactional behavior in the J2EE architecture.
The JTA specification defines the contracts
between applications, application servers,
resource managers, and transaction manager.
The J2EE platform specification defines the
requirements for the J2EE transaction
management and runtime environment.
25
Java Transaction API (JTA)

JTA specifies standard Java interfaces between
a transaction manager and the distributed
transaction participants it coordinates:


applications, application servers, and resource
managers.
JTA defines interfaces that let applications,
application servers, and resource managers
participate in transactions regardless of their
implementations.
26
Java Transaction API (JTA)



A JTA transaction is a transaction managed
and coordinated by the J2EE platform.
A JTA transaction can span multiple
components and enterprise information
systems.
A transaction is propagated automatically
between components and to enterprise
information systems accessed by components
within the transaction.

For example, a JTA transaction may comprise a
servlet or JSP page accessing multiple enterprise
beans, some of which access one or more resource
managers.
27
Java Transaction API (JTA)




JTA transactions begin either explicitly in code or
implicitly by an EJB server.
A component can explicitly begin a JTA transaction
using interface javax.transaction.
Main benefit of using JTA transactions is the ability to
combine multiple components and enterprise
information system accesses into one single
transaction with little programming effort.
The J2EE platform propagates transactions between
multiple components and enterprise information
systems with no additional programming effort.
28
Client Tier Transactions


The J2EE platform does not require
transaction support in applets and
application clients, though like
distributed transactions, a J2EE product
might choose to provide this capability
for added value.
To ensure portability, applets and
application clients should delegate
transactional work to enterprise beans,
either directly or by way of the Web tier.
29
Web Tier Transaction
Guidelines



Servlets and JSP pages in a two-tier
application can access enterprise information
systems within the scope of a JTA transaction.
Servlets and JSP pages support only
programmatic transaction demarcation.
A servlet or JSP page can use JNDI to look up
a UserTransaction object (using the
standard defined name
java:comp/UserTransaction), and then
use the UserTransaction interface to
demarcate transactions.
30
Web Tier Transaction
Guidelines
Example illustrates the use of the JTA UserTransaction
interface to demarcate transactions within a Servlet:
Context ic = new InitialContext();
UserTransaction ut =
(UserTransaction)ic.lookup("java:comp/UserTransaction");
ut.begin();
// access resources transactionally here
ut.commit();
• Calling UserTransaction.begin associates the calling thread with a new
transaction context.
• Subsequent accesses of transactional resources such as JDBC
connections or resource adapter connections implicitly enlist those resources into
the transaction.
• The call to UserTransaction.commit commits the transaction,
transparently engaging the two-phase commit protocol if necessary.
31
Enterprise JavaBeans Tier
Transactions


Enterprise beans offer two types of transaction
demarcation: bean-managed and
container-managed.
In container-managed transaction
demarcation, six different transaction
attributes—


Required, RequiresNew, NotSupported,
Supports,Mandatory, and Never
An application component provider or
assembler specifies the type of transaction
demarcation and transaction attributes for the
methods of the enterprise beans in the
deployment descriptor.
32
Bean-Managed Transaction
Demarcation



Enterprise bean uses the
javax.transaction.UserTransact
ion interface to explicitly demarcate
transaction boundaries.
Session beans and message-driven
beans can choose to use bean-managed
demarcation
Entity beans must always use containermanaged transaction demarcation.
33
Bean-Managed Transactions


The following pseudocode illustrates the kind of fine-grained
control you can obtain with bean-managed transactions.
By checking various conditions, the pseudocode decides whether
to start or stop different transactions within the business method.
begin transaction ...
update table-a ...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c commit transaction
34
Enterprise Bean Using a JTA
Transaction
UserTransaction ut =
ejbContext.getUserTransaction();
ut.begin();
// perform transactional work here
ut.commit();
The UserTransaction interface is used the same way in the EJB tier as in the
Web tier except that the reference to the interface is obtained by calling
EJBContext.getUserTransaction instead of by way of a JNDI lookup.
35
Container-Managed
Transaction Demarcation



The EJB container manages transaction
boundaries for enterprise beans that use
container-managed transaction
demarcation.
A transaction attribute for an enterprise bean
method determines that method’s transactional
semantics, defining the behavior the EJB
container must provide when the method is
called.
Transaction attributes are associated with
enterprise bean methods in the bean’s
deployment descriptor.
36
Container-Managed
Transaction Demarcation



For example, if a method has a transaction attribute
RequiresNew, the EJB container begins a new JTA
transaction every time this method is called and
attempts to commit the transaction before the method
returns.
The same transaction attribute can be specified for all
the methods of an enterprise bean or different
attributes can be specified for each method of a bean.
Even in container-managed demarcation, an enterprise
bean has some control over the transaction.

For example, an enterprise bean can choose to roll back a
transaction started by the container using the method
setRollbackOnly on the SessionContext, EntityContext and
MessageDrivenContext object.
37
Benefits of using Container-Managed
Transaction Demarcation

The transaction behavior of an enterprise bean is
specified declaratively instead of programmatically.




This frees the application component provider from writing
transaction demarcation code in the component.
It is less error-prone because the container handles
transaction demarcation automatically.
It is easier to compose multiple enterprise beans to
perform a certain task with specific transaction
behavior.
An application assembler that understands the
application can customize the transaction attributes in
the deployment descriptor without code modification.
38
Transaction Attributes




A transaction attribute is a value associated
with a method of an enterprise bean that uses
container-managed transaction demarcation.
A transaction attribute is defined for an
enterprise bean method in the bean’s
deployment descriptor, usually by an
application component provider or application
assembler.
The transaction attribute controls how the EJB
container demarcates transactions of
enterprise bean methods.
In most cases, all methods of an enterprise
bean will have the same transaction attribute. 39
Transaction Attribute Settings

Required



Use as the default transaction attribute to ensure
that methods are invoked within a JTA transaction
Causes the enterprise bean to use existing
transactional context if it exists or to create one if
not
RequiredNew


Use when the results of the method must be
committed regardless whether the caller’s
transaction succeeds.
Logging is a good example
40
Transaction Attributes

Supports


Mandatory


Use when the method absolutely requires an existing
transaction
Never


Use for methods that either do not change the database or
update atomically and it does not matter if the updates occur
in a transaction
Use to ensure that a transactional client does not access
methods that are not capable of participating in a transaction
NotSupported

Use when an enterprise bean accesses a resource manager
that either does not support external transaction demarcation
or not supported by J2EE.
41
University Registrar
Session Bean Example
42
JTA Resources

Sun’s Resources:

Java Transaction Architecture Spec:
http://java.sun.com/products/jta
43
The Web Tier


A J2EE application’s Web tier makes the
application’s business logic available on
the World Wide Web (WWW).
The Web tier handles all of a J2EE
application’s communication with Web
clients, invoking business logic and
transmitting data in response to
incoming requests.
44
The Purpose of the Web Tier




A server in the Web tier processes HTTP
requests.
In a J2EE application, the Web tier usually
manages the interaction between Web clients
and the application’s business logic.
The Web tier typically produces HTML or XML
content, though the Web tier can generate and
serve any content type.
While business logic is often implemented as
enterprise beans, it may also be implemented
entirely within the Web tier.
45
Web Tier Functions

The Web tier typically performs the following
functions in a J2EE application:



Web-enables business logic—The Web tier
manages interaction between Web clients and
application business logic.
Generates dynamic content—Web-tier
components generate content dynamically including
HTML, images, sound, and video.
Presents data and collects input—Web-tier
components translate HTTP PUT and GET actions
into a form that the business logic understands and
present results as Web content.
46
Web Tier Functions




Controls screen flow—The logic that determines
which “screen” (that is, which page) to display next
usually resides in the Web tier, because screen flow
tends to be specific to client capabilities.
Maintains state—The Web tier has a simple, flexible
mechanism for accumulating data for transactions and
for interaction context over the lifetime of a user
session.
Supports multiple and future client types—
Extensible MIME types describe Web content, so a Web
client can support any current and future type of
downloadable content.
May implement business logic—While many
enterprise applications implement business logic in
enterprise beans, Web-only, low- to medium-volume
applications with simple transactional behavior can
implement business logic entirely within the Web tier. 47
Traditional Web-Tier
Technologies



The earliest versions of the World Wide Web
relied on basic HTTP servers to serve static
HTML pages to HTML browsers.
Quickly became clear that dynamic content,
generated on demand, would make the Web a
platform for delivering applications as well as
content.
Several mechanisms were developed to allow
Web servers to generate content on demand,
all of which can be thought of as Web server
functional extensions.
48
Traditional Web-Tier
Technologies - CGI

Common Gateway Interface (CGI)


The earliest standard server extension mechanism was CGI,
which defines a type of stand-alone executable program used
by a server to produce dynamic content.
While CGI remains a popular option for Web applications, it
has some important limitations.



CGI has performance limitations - each HTTP request to a CGI
program usually results in the creation of a heavyweight process
in the host operating system.
CGI is also a simple interface that offers no portable support for
high-level system services, such as load balancing, scalability,
high availability, security, state maintenance, and resource
management, making scalable CGI solutions difficult to develop
and maintain.
CGI’s simplicity is a double-edged sword: It is easy to
understand, but it does not offer many portable system
services to the developer.
49
Web-Tier Technologies in the
J2EE Platform




Web-tier technologies in the J2EE platform provide the
benefits of server-side scripting, using compiled Java
classes in a standardized, secure, and vendor-neutral
environment.
A Web application is a collection of Web-tier
components, content, and configuration information,
which operates as a single functional unit.
The runtime support environment for a Web
application is called a Web container.
A Web application archive (.war) file contains all of
the class files and resources for the Web application,
along with an XML deployment descriptor file that
configures the application.
50
Web-Tier Technologies in the
J2EE Platform


The platform specification defines a contract
between the Web container and each Web
component, defining the component’s lifecycle,
the behavior the component must implement,
and the services that the server must provide
to the component.
The platform specification also defines two
types of Web component technologies:


Java Servlets (“servlets”) and
JavaServer Pages (JSP pages) technology.
51
Servlets and JSP

A servlet is a Java class that extends a J2EE server,
producing dynamic content in response to requests
from the server.


A JSP page is an HTML page with special markup that
provides customizable behavior for generating dynamic
content at runtime.


The server passes service requests to the servlet through the
standard interface javax.servlet, which every servlet must
implement.
A JSP page is usually translated into a servlet when it is
deployed.
JSP technology provides a document-centric, rather
than programmatic, way to specify dynamic content
generation.
52
The Web Container




A J2EE Web application runs inside a J2EE server’s
Web container.
The container manages each component’s lifecycle,
dispatches service requests to application components,
and provides standard interfaces to context data such
as session state and information about the current
request.
The Web container provides a consistent interface to
the components it hosts, so Web components are
portable across application servers.
Packaging and deployment of J2EE Web applications
are standardized, a Web application can be deployed
into any J2EE server without recompiling the code or
rebuilding the application archive.
53
Java Servlets

A Java Servlet is a Java class that extends a J2EEcompatible Web server.



Think of them as Java classes that can generate dynamic
HTML content using print statements
Similiar to CGI, servlets support a request and response
programming model.
Servlets offer some important benefits over earlier
dynamic content generation technologies.




Servlets are compiled Java classes, so they are generally faster
than CGI programs or server-side scripts.
Servlets are safer than extension libraries, because the Java
Virtual Machine (JVM) can recover from a servlet that exits
unexpectedly.
Servlets are portable both at the source-code level (because of
the Java Servlet specification) and at the binary level (because of
the innate portability of Java bytecode).
Servlets also provide a richer set of standard services than any 54
other widely adopted server extension technology.
JavaServer Pages (JSP)
Technology






JSP technology abstracts servlets to a higher level
Directly competes with Microsoft’s Active Server Pages
(ASP) technology
A JSP page is a document containing fixed template
text, plus special markup for including other text or
executing embedded logic.
The fixed template text is always served to the
requester just as it appears in the page, like traditional
HTML.
The special markup can take one of three forms:
directives, scripting elements, or custom tags
Think of JSP as “inside-out” servlets
55
Benefits of JSP






JSP pages easily combine static templates, including
HTML or XML fragments, with code that generates
dynamic content
JSP pages are compiled into servlets when requested,
so page authors can easily make updates to
presentation code. (can be precompiled if desired)
JSP tags for invoking JavaBean components manage
these components completely, shielding the page
author from the complexity of application logic
Developers can offer customized JSP tag libraries
JSP pages have all the benefits of Java technology,
including robust memory management and security
Provides enterprise-class scalability and performance 56
Speed Improvements with JSP

Separating content generation from
presentation



Using JSP technology, web page developers use HTML or XML
tags to design and format the results page.
If the core logic is encapsulated in tags and beans, then other
individuals, such as web masters and page designers, can edit
the JSP page without affecting the generation of the content.
Emphasizing reusable components



Most JSP pages rely on reusable, cross-platform components
(EJBs) to perform the more complex processing required of
the application.
Developers can share and exchange components that perform
common operations, or make them available to larger user or
customer communities.
The component-based approach speeds overall development
and lets organizations leverage their existing expertise and
development efforts for optimal results.
57
Speed Improvements with JSP

Simplifying page development with tags




Web page developers are not always programmers familiar
with scripting languages.
JSP technology encapsulates much of the functionality
required for dynamic content generation in easy-to-use, JSPspecific XML tags.
Standard JSP tags can access and instantiate JavaBeans
components, set or retrieve bean attributes, download
applets, and perform other functions that are otherwise more
difficult and time-consuming to code.
JSP technology is extensible through the
development of customized tag libraries


ver time, third-party developers and others will create their
own tag libraries for common functions.
This lets web page developers work with familiar tools and
constructs, such as tags, to perform sophisticated functions.
58
JSP - A Simple Application
This model basically replaces the CGI-BIN concept with a JSP page:
This method has the following advantages:
--It is simple and fast to program
--The page author can easily generate dynamic content based on the request and
state of the resources.
--This architecture works well for many applications, but it does not scale for a large
number of simultaneous Web-based clients accessing scarce enterprise resources,
since each must establish or share a connection to the content resource in question.
--For example, if the JSP page accesses a database, it may generate many
59
connections to the database, which can affect the database performance.
JSP - A Flexible Application
with Java Servlets
Web-based client may make a request directly to a Java Servlet, which actually
generates the dynamic content, wraps the results into a result bean and invokes
the JSP page. The JSP page accesses the dynamic content from the bean and
sends the results (as HTML) to the browser.
This approach creates more reusable components that can be shared between
applications, and may be implemented as part of a larger application.
It still has scalability issues in terms of handling connections to enterprise resources,
such as databases.
60
JSP - Scalable Processing with
Enterprise JavaBeans Technology
JSP page can also act as a middle tier within an Enterprise JavaBeans (EJB)
architecture. In this case, the JSP page interacts with back end resources
via an Enterprise JavaBeans component.
The EJB component manages access to the back end resources, which provides
scalable performance for high numbers of concurrent users.
For e-commerce or other applications, the EJB manages transactions and underlying
security. This simplifies the JSP page itself.
This model will be supported by the Java 2 Enterprise Edition (J2EE) platform.
61
Model-View-Controller (MVC)
An online store may require an HTML front for Web customers, a WML front for
wireless customers, a JavaTM (JFC) / Swing interface for administrators,
and an XML-based Web service for suppliers.
62
MVC Design Pattern
63
Separating Business Logic
from Presentation

Separating business logic from presentation has
several important benefits:




Minimizes impact of change—Business rules can be
changed in their own layer, with little or no modification to the
presentation layer.
Increases maintainability—Business logic expressed in a
separate component and accessed referentially can be
modified in one place in the source code, producing behavior
changes everywhere the component is used.
Provides client independence and code reuse—
Intermingling data presentation and business logic ties the
business logic to a particular type of client..
Separates developer Separating business logic and
presentation allows developers to concentrate on their area of
expertise.
64
Application Complexity vs.
Robustness
65
Model-View-Controller (MVC)
Architecture
Model 2 - Recommended
66
Model-View-Controller (MVC)
Architecture





Model 2 architecture integrates the use of both
servlets and JSP pages.
In this mode, JSP pages are used for the presentation
layer, and servlets for processing tasks.
The servlet acts as a controller responsible for
processing requests and creating any beans needed by
the JSP page.
The controller is also responsible for deciding to which
JSP page to forward the request.
The JSP page retrieves objects created by the servlet
and extracts dynamic content for insertion within a
template.
67
How do JSP Pages Work?







A JSP page is basically a web page with traditional HTML and bits
of Java code.
The file extension of a JSP page is .jsp rather than .html or .htm,
which tells the server that this page requires special handling that
will be accomplished by a server extension or a plug-in.
When a JSP page is called, it will be compiled (by the JSP engine)
into a Java servlet.
At this point the servlet is handled by the servlet engine, just like
any other servlet.
Servlet engine then loads the servlet class (using a class loader)
and executes it to create dynamic HTML to be sent to the
browser.
Servlet creates any necessary object, and writes any object as a
string to an output stream to the browser.
Next time the page is requested, the JSP engine executes the
already-loaded servlet unless the JSP page has changed, in which
case it is automatically recompiled into a servlet and executed. 68
How do JSP Pages Work?
69
The Servlet’s Job







Read explicit data sent by client (form data)
Read implicit data sent by client
(request headers)
Generate the results
Send the explicit data back to client (HTML)
Send the implicit data to client
(status codes and response headers)
70
The Need for JSP

With servlets, it is easy to








Read form data
Read HTTP request headers
Set HTTP status codes and response headers
Use cookies and session tracking
Share data among servlets
Remember data between requests
Get fun, high-paying jobs
But, it sure is a pain to


Use those println statements to generate HTML
Maintain that HTML
71
The JSP Framework

Idea:



Use regular HTML for most of page
Mark servlet code with special tags
Entire JSP page gets translated into a servlet (once), and
servlet is what actually gets invoked (for each request)
<DOCTYPE ...>
<HTML>
<TITLE>Order Confirmation</TITLE>
<LINK REF=STYLESHEET
HREF=“JSP-Styles.css”
TYPE=“text/css”>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
Thanks for ordering
<I><%= request.getParameter(“title”) %></I>!
</BODY>
</HTML>
72
Advantages of JSP Over
Competing Technologies

Versus ASP or ColdFusion



Versus PHP



Better language for dynamic part
Portable to multiple servers and operating systems
Better language for dynamic part
Better tool support
Versus pure servlets




More convenient to create HTML
Can use standard tools (e.g., DreamWeaver)
Divide and conquer
JSP programmers still need to know servlet
programming
73
Advantages of JSP
(Continued)

Versus client-side JavaScript (in
browser)




Versus server-side JavaScript (e.g.,
LiveWire, BroadVision)


Capabilities mostly do not overlap with JSP, but
You control server, not client
Richer language
Richer language
Versus static HTML


Dynamic features
Adding dynamic features no longer "all or nothing"
decision
74
Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer Pages">
<META NAME="description"
CONTENT="A quick example of JSP
expressions.">
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
75
Example
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Server: <%= application.getServerInfo() %>
<LI>Session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
76
Example: Result
77
Most Common Misunderstanding:
Forgetting JSP is Server-Side Technology

Very common question



Why doesn’t this question make sense?



I can’t do such and such with HTML.
Will JSP let me do it?
JSP runs entirely on server
It doesn’t change content the client (browser) can handle
Similar questions

How do I put a normal applet in a JSP page?


How do I put an image in a JSP page?


Answer: send an <APPLET…> tag to the client
Answer: send an <IMG …> tag to the client
How do I use JavaScript/Acrobat/Shockwave/Etc?

Answer: send the appropriate HTML tags
78
2nd Most Common Misunderstanding:
Translation/Request Time Confusion

What happens at page translation time?


What happens at request time?


JSP constructs get translated into servlet code.
Servlet code gets executed. No interpretation of JSP
occurs at request time. The original JSP page is
totally ignored at request time; only the servlet that
resulted from it is used.
When does page translation occur?


Typically, the first time JSP page is accessed after it
is modified. This should never happen to real user
(developers should test all JSP pages they install).
Page translation does not occur for each request. 79
JSP/Servlets in the Real World:
Airlines











Delta Airlines
United Airlines
AirTran
American
Airlines
British Airways
KLM
Air China
Saudi Arabian
Airlines
Iceland Air
80
JSP/Servlets in the Real World:
Financial Services











American
Century
Vanguard
Fidelity
NY Stock Exchange
First USA Bank
Royal Bank of
Scotland
Banco Popular de
Puerto Rico
Bank of America
China
Construction Bank
81
JSP/Servlets in the Real World:
Retail









Sears.com
Walmart.com
SamsClub.com
Macys.com
llbean.com
Kohls.com
Ikea.com
REI.com
Longaberger.com
82
JSP/Servlets in the Real World:
Search/Portals





Google
Half.ebay.com
Netscape.com
Excite.com
Dice.com
83
Summary


JSP makes it easier to create and maintain
HTML, while still providing full access to servlet
code
JSP pages get translated into servlets



You still need to understand servlets





It is the servlets that run at request time
Client does not see anything JSP-related
Understanding how JSP really works
Servlet code called from JSP
Knowing when servlets are better than JSP
Mixing servlets and JSP
Other technologies use similar approach, but
aren't as portable and don't let you use Java for
the "real code"
84
JSP Resources

Sun’s website




Free Online Books




http://java.sun.com/products/jsp/docs.html
J2EE 1.4 Tutorial
Search the site for JSP – there are whitepapers, articles,
blueprints (best practices), etc.
http://www.coreservlets.com
Free Online books – they are the previous rev but most of the
information is relevant and the author indicates where it is
not.
Register with email address
Others:


http://www.jsptut.com
http://www.theserverside.com/articles/index.tss
85
Download