An Empirical Study and Implementation of UI Layer in a J2EE Application: A Case Study

rangaleclickΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

120 εμφανίσεις



A
n
Empirical

Study

and

Implementation

of UI Layer in a
J2EE

Application
: A Case Study



(Starred Paper)


By

Maqbool Khan




Committee


Dr. Donald Hamnes
(advisor)

Dr. Ramnath

Sarnath

Dr. Richard Heath
(advisor)



































-

2
-

INDEX

INTRODUCTION

________________________________
_________________


Abstract

________________________________
_____________________________

-

5
-

Introduction

________________________________
__________________________

-

5
-

Reading this paper
________________________________
_____________________

-

7
-

Scope

________________________________
_______________________________

-

8
-

Things to know

________________________________
_______________________

-

9
-

INTRODUCTION TO TECH
NOLOGY

_____________________________

-

11
-

A telescopic introduction to J2EE web application development

_______________

-

11
-

Typical J2EE applicatio
n architecture

________________________________
____

-

13
-

Introduction to Servlets

________________________________
________________

-

16
-

Introduction to JSP

________________________________
___________________

-

21
-

Challenges of web application development

_______________________________

-

25
-

Need for MVC

________________________________
______________________

-

29
-

DISCUSSION ON STRUTS

AND JSF

_____________________________

-

33
-

An example application


Web store

________________________________
_____

-

33
-

Struts

________________________________
______________________________

-

34
-

Java Server Fa
ces (JSF)

________________________________
_______________

-

43
-

Which framework should I use?

________________________________
_________

-

47
-

FRAMEWORK DESIGN AND

IMPLEMENTATION

___________________

-

52
-

Goals

________________________________
______________________________

-

52
-

Why another framework?

________________________________
______________

-

52
-

Introduction to the framework

________________________________
__________

-

53
-

How to use the framework?

________________________________
____________

-

59
-


-

3
-

Cooks Tour of the Framework

________________________________
__________

-

61
-

Need for Re
flection

________________________________
__________________

-

100
-

Future improvements

________________________________
________________

-

104
-

Final Words

________________________________
________________________

-

105
-

CO
NCLUSION

________________________________
______________

-

108
-

APPENDIX A

________________________________
_______________

-

110
-

Glossary

________________________________
__________________________

-

110
-

APPENDIX B

________________________________
_______________

-

113
-

UML Diagrams (left out from before)

________________________________
___

-

113
-

ACKNOWLEDGEMENTS

________________________________
______

-

115
-

BIBLIOGRAPHY

________________________________
_____________

-

116
-
























-

4
-

LIST OF FIGURES


F
IGURE
1:

T
YPICAL LAYERING IN A

J2EE

APPLICATION

________________________________
______

-

14

-

F
IGURE
2:

R
EQUEST HANDLING AND
PROCESSING IN
S
TRUTS

________________________________
__

-

35

-

F
IGURE
3:

JSF

LIFE CYCLE

________________________________
____________________________

-

44

-

F
IGURE
4:

F
RAMEWO
RK

S
P
ACKAGE STRUCTURE
________________________________
___________

-

63

-

F
IGURE
5:

L
AYERED VIEW OF THE F
RAMEWORK

________________________________
____________

-

64

-

F
IGURE
6:

F
RAMEWORK

S CLASS INTERACTION
DIAGRAM

________________________________
____

-

65

-

F
IGURE
7:

F
RAMEWORK

S FLOW
-

A
CTIVITY DIAGRAM

________________________________
______

-

66

-

F
IGURE
8:

F
RAMEWORK

S FLOW
-

S
EQUENCE DIAGRAM

________________________________
_____

-

69

-

F
IGURE
9:

F
RONT CONTROLLER
S
ERVLET

________________________________
________________

-

73

-

F
IGURE
10:

A
PPLICATION CONTROLLE
R

________________________________
__________________

-

74

-

F
IGURE
11:

C
ONTROLLER IMPLEMENTA
TION

________________________________
______________

-

75

-

F
IGURE
12:

F
INAL CONTROLLER IMPL
EMENTATION

________________________________
_________

-

77

-

F
IGURE
13:

C
ONVERTER INTERFACE

________________________________
____________________

-

78

-

F
IGURE
14:

C
ONVERTER IMPLEMENTAT
ION

________________________________
_______________

-

79

-

F
IGURE
15:

F
INAL CONVERTER IMPLE
MENTATION

________________________________
__________

-

80

-

F
IGURE
16:

I
NTERCEPTOR INTERFACE

________________________________
___________________

-

82

-

F
IGURE
17:

F
INAL INTERCEPTOR IMP
LEMENTATION

________________________________
_________

-

84

-

F
I
GURE
18:

V
ALIDATOR INTERFACE

________________________________
_____________________

-

85

-

F
IGURE
19:

V
ALIDATOR IMPLEMENTAT
ION

________________________________
_______________

-

86

-

F
IGURE
20:

F
INAL VALIDATOR IMPLE
MENTATION

________________________________
__________

-

87

-

F
IGURE
21:

V
IEW INTERFACE

________________________________
__________________________

-

88

-

F
IGURE
22:

F
INAL VIEW IMPLEMENTA
TION

________________________________
_______________

-

88

-

F
IGURE
23:

C
ONTEXT OBJECTS

________________________________
_________________________

-

90

-

F
IGURE
24:

C
ORE OBJECTS

________________________________
____________________________

-

92

-

F
IGURE
25:

F
INAL LOGGER IMPLEMEN
TATION

________________________________
_____________

-

93

-

F
IGURE
26:

A
NNOTATION


A
EXPOSE

________________________________
___________________

-

95

-

F
IGURE
27:

A
NNOTATION


A
DOMAIN
O
BJECT

________________________________
_____________

-

95

-

F
IGURE
28:

A
NNOTATION


A
INTERCEPTOR

________________________________
_______________

-

96

-

F
IGURE
29:

A
NNOTATION


A
VIEW

________________________________
_____________________

-

96

-

F
IGURE
30:

A
NNOTATION


A
SCOPE

________________________________
____________________

-

97

-

F
IGURE
31:

A
NNOTATION


V
ALIDATOR ANNOTATIONS

________________________________
_____

-

98

-

F
IGURE
32:

P
LUGGABLE SELECTOR IM
PLEMENTATION

________________________________
______

-

103

-

F
IGURE
33:

E
XECUTION ERRORS


CLASS DIAGRAM

________________________________
________

-

113

-

F
IGURE
34:

F
INAL CONFIGURATION C
OMPONENT IMPLEMENTAT
ION

___________________________

-

113

-

F
IGURE
35:

F
RAMEWORK

S RUN TIME EXCEPTION
S

________________________________
________

-

114

-

F
IGURE
36:

F
RAMEWORK

S CHECKED EXCEPTIONS

________________________________
________

-

114

-













-

5
-

Chapter 1


Abstr
act


T
he re
cent times has
seen

the World Wide
Web

(WWW)

emerge as
a

major platform for
developing UI for enterprise applications
, with Java 2 Platform Enterprise Ed
i
tion (J2EE)
establishing itself as the leading
enabling
technology
.

This paper
is

an a
t
temp
t to present

what has
historically been done in this

arena of J2EE web application develo
p
ment by

briefly discuss
ing technologies and frameworks like Servlets, JSPs,

Struts and JSF
,

and
by

de
sign
ing

and devel
op
ing

a J2EE web application framework
by

descri
b
ing

its d
e
sign
in detail.
The resulting paper
would
serve
to

augment

some of
the already available
pra
g
matic reference on

J2EE web application develo
p
ment.


I
ntroduction


During the last decade

the world has witnessed a revolution
in the form of

the World

Wide Web (WWW)
, with
t
he WWW see
i
n
g

an u
nparalleled

and remarkable

growth

and
gradually

becoming

an inseparable part
of
our daily lives
.

The

recent

advent of
sta
n
dards

and technologies

like
Web 2.0

[28]
, JSR
-
168 po
r
tlets,

Java 2 Platform Enterprise Editio
n
(J2EE)

[2]
, .Net, A
synchronous
J
avaScript and
X
ML (AJAX) [15]
, etc.,

has made this
revolution

even

stronger

and

has created a wave in the software industry.

T
his stat
e
ment
becomes obvious when we look
at
the
stupendous
success Google

and other web based

businesses have achieved in the past few

years.

Looking at the cu
rrent state of a
f
fairs
,

I
am confident

that
the WWW
will

continue to grow and
will
be used as a pla
t
form
to

shar
e

information
,

develop UI for enterprise applications
,

and
also
to develop
ap
plic
a
tion
software like MS Word, etc.




The WWW

was
originally

designed with the intent of
just
sharing inform
a
tion

but has
also been very widely used
as a platform to port

user interface (
UI
) for enterprise applic
a-
tions

like Amazon, etc
.

and also for dev
eloping dynamic web applications.

Many
altern
a-
tives

were
proposed and used

to develop the
s
e dynamic

UI
s

but none of them offered a

-

6
-

simple, efficient
,

scalable

and maintainable

way of building web application.

A
fter a p
e-
riod of frustration J2EE came into
the market and soon
established itself as a leading
technology for
both
web
and enterprise application
development.

J2EE is
a
standard
from Sun and other industry heavy weights like IBM, Oracle, BEA, etc
.

and is essentially
a model for d
e
veloping distribu
ted applications based on well
-
defined components that
can automatically take advantage of sophisticated platform se
r
vices.

J2EE provides two
very important technologies called Java Server Pages (JSP)

[5]

and Servlets

[3]

using
which developers can build
robust and scalable dynamic web applic
a
tions with minimum
of effort.

However, because of the stateless nature of HTTP
[8]
and coarse
-
grained r
e-
quest
-
response model
,

develop
ing a complex web application i
s still a challenge

and the
lack of good

framework
l
eaves the developer t
o struggle and wrestle with
details.


This complexity is not due to the JSP and Servlet API but
is

because of

the

lack of proper
design patterns

and framework

[26
,
3
8
]

specific to the domain

of web application deve
l-
opment
.

A robust a
nd scalable system cannot be built just by using the latest and greatest
technology
, but

rather

requires a solid design.

This demanded the need for standard d
e-
sign pa
t
terns and more so for a
f
ramework to build dynamic web applications that
will

simplify d
evelopment and help

b
uild robust and scalable system
,

and today we have an
immense number of frameworks available with Struts

[2
9
]

and JSF
[7]
being the most
popular ones.



With this effort, I am trying to put together what has historically been done in t
his arena,
b
riefly look at Struts and JSF and most importantly

d
e
sign and implement a
pattern
-
oriented
,

production
-
ready J2EE web application framework.

The design and impleme
n-
tation of this framework forms the crux of this

paper
,

not because
this framewo
rk is the
best thing that has happened to J2EE web application development but

because my d
e-
sign narrative substantiates the design decisions that I have made while designing this
fram
e
work.

I earnestly hope
that
this paper would prove to be a very v
aluab
le resource
for anyone who is
looking to

use a good and
simple
-
to
-
use framework or

to
develop
a
web framework

or to use design patterns to come up with simple, flexible, elegant and
reu
s
able designs for web applications.



-

7
-

Reading this paper


Below is an ou
tline of what the paper is trying to accomplish:

1.

Present a background on J2EE web application development by introducing you
to technologies like Servlets and JSPs and talk about their strengths and wea
k-
nesses.

2.

Give a brief introduction to
J2EE web applica
tion frameworks like
Struts and JSF
and discuss their strengths and weaknesses.

3.

Design and develop a
J2EE
web application framework

to resolve
a
few of the
problems
discussed in the earlier part of the document

and more importantly to
provide

a

pragmatic r
eference for J2EE web application framework development.
T
hough the

developed framework tries to solve some of the
we
a
k
nesses
or lim
i-
tations faced by either Struts or JS
F or both,

it is not the intent of this fram
e-
work or this paper to either
be
better or
to

be a

replace
ment for either of

these
frameworks.

Both these frameworks are very mature and robust in comparison
to framework developed here. The framework developed here is for educational
purposes only, but it could very well be extended into a product
ion level fram
e-
work.


To provide a better flow

and

reading experience the
paper has been d
i
vided into four
chapters

with each chapter having a specific set of responsibility. Below is a
brief
d
e-
scription of what each chapter is
trying to a
c
complish
:


Chapt
er 1:

Provides an introduction to the paper, defines the scope for the
research,
scope for the document, scope for the discussion on Struts and JSF, scope for the web
applic
a
tion framework that is being developed as

a

part of this paper

and finally provide
s
a brief

definition
for

some of the terms used through
out the paper.


Chapter 2:

Provides an introduction to J2EE
,
Servlets and JSPs
. The chapter also

d
i
s-
cusses the shortcomings of both Servlets and
JSPs, presents the challenges faced in web
application d
evelopment that are not faced in the traditional GUI application develo
p-
ment and finally discusses how MVC fits into the design of web a
p
plication
s
.


-

8
-


Chapter 3:

Presents Struts and JSF the most popular J2EE web application frameworks
available

today,

discu
sses

their strengths and weaknesses and finally provides a brief
comparison of these frameworks.


Chapter 4:

This chapter f
orms the crux of this paper

and
understandably is the longest
chapter in this paper.
Below are the goals for this chapter:



Substantia
te

the development of
a

new framework



Provide

an introduction to the framework

being developed

by outlining and e
x-
plaining its features



Provide a tutorial on how to use the

developed

framework



Present a cook’s tour to the design of the framework by talking

about
its

design

in
de
tail



List the f
uture improvements



Conclude

by talking about the design characteristics of the developed fram
e
work


The
primary
goal of this chapter is to provide a cook

s tour to the design of the
developed
framework, which I believ
e would serve as a pragmatic reference for people inte
r
ested in
J2EE web applic
a
tion framework development.


Chapter 5:

C
onclu
des

the paper

by summarizing
the research that

has be
en done as a part
of this paper and by

summarizing

the d
ocument
.


Scope


Befo
re I get too deep into the paper
, I want to define the
scope for my research, for this
document, for the
discussion on

JSF and Struts

and

f
i
nally

for the framework
design and
implementation.


Scope of research

The

scope of my research has been extensive as

I have looked into all the technologies
that J2EE has to offer along with some of the popular appl
i
cation servers available for

-

9
-

this platform.

I have also looked into web frameworks other than Struts and JSF and
have learnt a lot from them.

Scope of thi
s document

The document

provide
s

a brief introduction to various technologies and fram
e
works like
Servlets, JSPs, Struts and JSF. The introduction provided here is brief

because discussing
just one technology like JSP would warrant a book of its own

and is

beyond of scope of
this document
. T
he
sole
intent

of th
is

document

while discussing any technologies and
fram
e
works

is to give you
a
feel of
it

before we
talk about

its

strengths and weak
nesses.
At the same time
,

the document

takes care of

point
ing

you to

a

proper

reference
or r
e-
source
for further d
e
tails

whenever needed
.



Discussion on

JSF and Struts


The document presents a brief introduction to these frameworks by talking about the
main components involved, the flow of how HTTP request is processed and

lists their
strengths and weakness by supporting it with examples and references.


Framework design and implementation


T
he

framework
’s

design and implementation
forms

the crux of this paper.

Hence, I have
spent a lot of time designing and implementing t
his fram
e
work and have also described
it

in detail.


This statement should become evident when you would look at the framework
code and at
the
chapter

which describes the
framework design and implementation
,
which

forms
a

half of this document.


Things t
o

know


Dynamic web application
:


It

is an application in which the
web
page
’s

content is d
y
na
m-
ically generated on the fly based on the business logic of the application
,

as against a sta
t-
ic web application where the content
is constant
.



-

10
-

Servlet
:


It
is a

J2EE component, which runs inside a Servlet container

[3]
.

It acts as an
intermediary between any HTTP clients and your server side application and provides the
developer with the capability to extend the web server by accessing business systems, etc.


J
SP
:


It
is built on the Servlet technology but provides a way to mix HTML

[9], Java
S-
cript [11]

and Java code and this makes it a simple and productive way to create dynamic
web applications.


J2EE Application Server
:


It
is an application server, which adh
eres to the J2EE standard
and provides all the services specified by the standard but may also provide more.


Framework
:


It
is a set of cooperating classes that make up a reusable design for a sp
e
ci
f-
ic

class of software [
38
].

A framework dictates the arc
h
i
tecture of your application.


Design pattern
:


It
is a general technique to solve a class of related pro
b
lems.

It provides
a general structure of a solution, in other words it is a meta
-
solution to a class of pro
b-
lems.


Model view controller (MVC)
:


It
is a
n architectural or a

com
pound pattern, which pr
o-
vides a

way to decouple the data, view and the

related

proces
s
ing

[24]
.


Reflection
:


It
is the ability of a running p
rogram to examine itself and it
s software env
i-
ronment, and to change what it does depe
nding on what it finds

[33,
42]
.


Annotations
:


It is
a way to provide meta
-
data about your program. They are modifiers,
which could be applied to packages, types, fields, methods, paramet
ers and even var
i
a-
bles [
58
].


Please look at Appendix
A for more det
ails






-

11
-





Chapter 2


Introduction to Technology


A telescopic i
ntroduction to J2EE web application develo
p
ment


J2EE is a platform for developing distributed enterprise software applic
a
tions.

It is an
attempt from Sun and other industry heavy weights t
o sta
n
dardize things that are required
to make enterprise applications portable across application servers and support systems,
to allow vendors to int
e
grate their services into the Java environment in a standard way
and finally to prevent enterprise devel
opers from wasting their valuable time re
-
creating
utilities that really
is plumbing

[2]
.

This

enabl
es

the

enterprise software developers
to
focus their efforts on the business logic of their systems.

In other words,
J2EE

is a spec
i-
fication which
provide
s

the fo
l
lowing:

i.

A

standard platform to host
enterprise

applic
ations

ii.

A
n application server that supports the latest
J2EE
specification

and

a compatibi
l-
ity test suite to test

it
s compatibility with the

specification

iii.

A
n application programming model to help
individuals learn how to develop di
s-
t
ributed applications using J2EE




Below is the set of API’s provided by
both

J2EE
and

J2SE:


Java Servlets:


Provides an object oriented API to build dynamic web a
p
plications.


Java Server Pages:


Provides a template d
riven approach to building dynamic web appl
i-
cations.



-

12
-

Enterprise JavaBeans (EJB):


Specifies a component framework for multi
-
tier distributed
applications. It provides various benefits like object poo
l
ing, resource pooling, container
-
managed transactions,
thread safety, etc. It was de
-
facto standard to define server side
components before the i
n
troduction of enterprise frameworks like Spring

[49]
.


JDBC 3.0:


Provides database programming facilities to work with dat
a
base connections,
transactions, cursors,
etc


Java Message Service (JMS):


A standard implemented by different ve
n
dors to provide
message oriented middleware.


Java Transaction API (JTA):


Provides a way to implement distributed and container
managed transactions.


Java Naming and Directory Inter
face (JNDI):


Provides standardized a
c
cess to different
types of directory services like LDAP.


Java Mail:


A Platform independent and protocol independent framework to build email
application in Java.


Java API for XML Parsing (JAXP):


Provides an abstrac
tion for XML parsing and tran
s-
formation APIs.


Java Connector Architecture (JCA):


Integrates J2EE applications with other enterprise
information systems or legacy systems.


Java Authentication and Authorization Service:


Provides authentication and author
iz
a-
tion mechanisms to J2EE applications.


Interface Definition Language (IDL):


Allows J2EE or Java application components to
invoke CORBA objects via IIOP.



-

1
3
-

RMI
-
IIOP:

An RMI implementation over IIOP.


J2EE platform is
essentially a set of
containers;

a

c
ontainer provides the runtime env
i-
ronment to manage the J2EE components developed accor
d
ing to the API specifications
and also to provide various other services like transaction management, etc.

The four
containers in which all the J2EE APIs fall are the
EJB container, web container, applet
container, and

a
p
plication client controller
.

o

EJB Container:


Hosts the EJB components and provides various services like
thread management, session management, declarative transactions, etc.

o

Web Container:


Hosts Serv
lets and JSPs and provides various services like se
s-
sion management, etc.

o

Applet Container:

Hosts applets.

o

Application Client controller:


Hosts standard java applications.


Typical J2EE application architecture


J2EE

application architecture is dictated

by
whether
it
is distributed or non
-
distributed.

Distributed architectures are

generally

more complex than their non
-
distributed counter
parts and
are also
less
acquiescent

to

OO d
e
sign
than

their counter parts.

With the advent
of web services and

wide
acceptance of web applications as a standard way to access e
n-
terprise sy
s
tems

along with

strong clustering support for application servers

the
non
-
distributed

architecture is the o
ne that is mostly used

today
.

We will

also be lookin
g into
the details of t
he non
-
distributed
architecture and
the
not distributed architecture.

We
will

be
look
ing into

it from a layers stan
d
point and not tiers because tiers tend to
be a

more physical separation, where
as layers tend to be more logical

separation
.


Layering is
al
so an archite
c
tural pattern which lets decompose the application into groups of subtasks
in which each group is defined at a particular level o
f abstraction

[37
,
44]
.


A typical J2EE application architecture is based on the principle of sof
t
ware layering a
s it
has the following benefits:


-

14
-

1.

Helps understand one layer as a coherent whole without understanding the other
layers involved and this immensely helps in d
i
vi
di
ng the work and responsibilities
within a team and within the organization

2.

Makes it easy to su
bstitute one laye
r implementation with an
other

3.

Helps promote standardization

4.

Each lay
er is built on top of the other


The typical software layers in a J2EE application are:



Figure
1
:
Typical layering i
n a J2EE application



Data Access Object Layer:

Provides read, write, update and delete services for the appl
i-
cations data.

The application data can either come from a database, file or XML source.


Business logic layer:


Focuses on the application’s bus
iness requirements and contains
domain

objects and business services.

It receives requests from the presentation tier, pr
o-
Presentation la
yer

Servlets/ JSPs

Applets

GUI

Deployment layer

EJB

Web se
r
vices

RMI


Business logic layer

Data access layer

DAO’s
=
XAO’s
=
FAO’s
=
f
n
f
r
a
=
s
t
r
u
c
t
u
r
e
=
=
c
o
m
p
s
=
=
=
=
=
=
=
=
=
r
t
i
l
i
t
i
e
s
=

-

15
-

cesses the business logic based on the r
e
quests, and mediates access to the data access
objec
t layer
.


Data Transfer Objects:


A lig
ht weight structure of related information used to optimize
data transfer across layers.


This is sometimes also termed as a Value Object (VO).


Deployment Layer:


Wrap
s the business
logic

into
standard J2EE comp
o
nents like EJB to
publish to remote systems

or make use of the system level services like security ma
n-
agement, transaction management, and r
e
source management.


Presentation layer:


This layer exposes the business
-
logic tier services to the users.

This
way the client tier is loosely coupled to the

business logic layer.


This layer knows how to
process a client request, how to interact with the business
-
logic layer, and how to switch
between the views.

A
good implementation of the presentation layer
will

have the fo
l-
lowing features
:

i.

Navigation

ii.

Vali
dation

iii.

Custom tags to build
complex
user interfaces

iv.

Security

v.

S
calability

vi.

Maintainability


Architectural components or utilities layer:


Provides generic application wide utilities

like logging, thread pools, etc
.


A more detailed discussion on J2EE or any
of its APIs other th
a
n Servlets and JSPs is
beyond the scope of this document
.


Th
e
s
e

could very well be read from the vast amount
of literature that’s
already
available.


The bibl
i
ography has listed some resource
s

which
you
will

find valuable to learn mor
e about this

interesting

technology
.


Here
on we will be concentrating more on the web application development or present
a-
tion
layer

of a J2EE application
. In order to do this we would first look at the challenges

-

16
-

faced by web application development

(using

Java)

in
and

later look at
technologies like
Ser
v
lets and
JSPs

and frameworks like Struts and JSF
.





Introduction to Servlets


This was

the first web t
echnology introduced by J2EE.

Servlets

provide
s

a platform i
n-
dependent, component based method of bui
lding web applications.

Servlets were a sup
e-
rior technology to the already existing tec
h
nologies like Common Gateway Interface
(CGI) because instead
of
wri
t
ing server side scripts in languages like

Perl and C to spawn
a process

for each request to the ser
ver, Servlets offered a much less expensive and
el
e-
gant

alternative
by
making use of multi
-
threading and
object
pooling
.


Servlets run

inside
a container called the w
eb container, which is responsible for
delegating

the

HTTP r
e-
quest to the Servlet.
The web

container
is multi
-
threaded and handles each HTTP request
in a separate thread and eliminates the need to
create a new process
. The web container
also i
m
proves performance by pooling the Servlet instances.


Most of the web containers
available
today use a

thread pool to serve the requests and eliminates the cost of cr
e
ating
a thread for each request

which is nothing when compared to the cost of creating a pr
o-
c
ess
.

Servlets are written in

the

Java language and are part of a J2EE application.


Hence,
they h
ave all the power of Java language, access to all the J2EE APIs, r
e
sources managed
by the application server
.

Finally, Servlets
promote OO web develo
p
ment

which is not
seen in other competing technol
o
gies
.


To make things clear let me show you a simple Se
rvlet
:


p
ublic class EStore extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
Ser
v
letException, IOException {



PrintWriter out = response.get
Writer();


-

17
-

out.println("<html><head><title>Wrox

Shopping

Mall</title></head><body><table
width='600'><tr><td width='20%'>");



ArrayList cats = (ArrayList) getServletContext().getAttribute("cats");



for (int i=0; i< cats.size(); i++) {



Ca
tegory curCat = (Category) cats.get(i);



out.println("<a href=");



out.println(request.getRequestURL());



out.println("?catid=");



out.println(curCat.getId());



out.println(">");



out.printl
n(curCat.getName());



out.println("</a><br/>");



}



out.println("</td><td><h1></h1><table border='1'><tr><th align='left'>" +





"Item</th><th align='left'>Price</th><th align='left'>Order</th></tr>");



String selectedCat = reque
st.getParameter("catid");



if (selectedCat == null)
{



selectedCat = "1";


}



ArrayList items = (ArrayList) EShop.getItems(selectedCat);



for (int i=0; i< items.size(); i++) {



Product curItem = (Product) items.get(i);



out
.println("<tr><td>");



out.println(curItem.getName());



out.println("</td><td>");



out.println(dispPrice(String.valueOf(curItem.getPrice())));



out.println("</td><td><a href='");



out.println(request.getContextPath());



out.println("/example3/shopcart.jsp?action=buy&sku=");



out.println(curItem.getSku());



out.println("'<b>BUY</b></a></td></tr>");



}



out.println("</table></td></tr></table></body></html>");


}




public void destroy() {



super
.destroy();



getServletContext().removeAttribute("cats");


-

18
-


}




public void init() throws ServletException {



super.init();



getServletContext().setAttribute("cats", EShop.getCats());


}




private String dispPrice( String price) {



int len = price.le
ngth();



if (len <= 2)

{




return price;



}



else
{




return "$" + price.substring(0,len
-
2) + "." + price.substring(len
-
2);



}


}

}

Fragment
1


The above
Servlet

code after being translated by the
Servlet

container is rend
ered by the
browser as show below:




-

19
-


So as seen in the code snippet above to develop a Servlet you need to e
x
tend the HTTP
S-
ervlet class which in turn implements the Servlet interface.
The intent of the above exa
m-
ple is to give you a feel of the Servlet t
echnology and
to
use

it

as a basis for di
s
cussing its
strengths and weaknesses. Hence,
it
has intentionally

been

kept simple.

To understand

this technology better

please look at resources

[3] and

[59
]
listed in the bibl
i
ography
se
c-
tion.

Short comings


As S
ervlets are nothing but Java objects they proved to be very good at invoking business
logic

but failed to provide a clean solution for the fo
l
lowing:



1.

T
he inability to see the
generated markup

(HTML, CSS and Java
script that would
be rendered by the browse
r)

at the development time

makes
it difficult to
visua
l-
ize the web page under development.
This

makes it very difficult to create co
m-
plex web pages (l
ots of HTML, CSS and Java
script).

For instance the Fragment 1 generates the markup shown below, but this i
s not
e
v
ident when you look
at
the Servlet

code. This limitation
makes it hard to d
e
ve
l-
op co
m
plex interfaces.

<html>

<head>

<title>Wrox Shopping Mall</title>

</head>

<body>

<table width="600">

<tr>

<td width="20%">


<a href="http://localhost:7080/WebStore/
withoutframework/example3/estore.jsp?catid=1">


Systems

</a>

<br/>


<a href="http://localhost:7080/WebStore/withoutframework/example3/estore.jsp?catid=2">


Software

</a>

<br/>


<a href="http://localhost:7080/WebStore/withoutframework/exampl
e3/estore.jsp?catid=3">


Books

</a>


-

20
-

<br/>


</td>

<td>

<h1></h1>

<table border="1">

<tr><th align="left">Item</th><th align="left">Price</th><th align="left">Order</th></tr>


<tr>


<td>Pentium 4
-

4 GHz, 512 MB, 300 GB</td>


<td>$989.99</td>


<td><a href="/WebStore/example3/shopcart.jsp?action=buy&sku=232">


<b>BUY</b></a>


</td>

</tr>



<tr>


<td>AMD Opteron
-

4 GHz, 1 GB, 300 GB</td>


<td>$1200.99</td>


<td><a href="/WebStore/example3/shopcart.jsp?action=buy&sku=238">



<b>BUY</b></a>


</td>

</tr>


</table>

</td>

</tr>

</table>

</body>

</html>


2.

As you can see in the
Fragment 1
a pure Servlet approach ends up
intermixing the
HTML and Java code
. This complicates maintenance because web interfaces are
prone to change and
this inter
-
mixing

of HTML and Java code

makes it difficult
to change the markup

and vice
-
versa.


T
his also forces you to perform your complete suite of testing again

because
Ser
v
lets

contain control code (Java code) and a change in the HTML code might
have

unintentionally introduced a bug in the control code.

This is mostly
an
ove
r-
kill

for situations where only the HTML code has been modified.

3.

The intermixing of markup and Java code promotes p
oor division of responsibi
l-
ity amon
g the developers in the compan
y
, because most of the good Web deve
l-
opers are not good with their Java and OO skills and vice
-
versa.

“In fact, this process hopelessly bound together the work of a Web page design
with the work of server logic design and made the programmer responsible fo
r
both”

[42] (page 11).


-

21
-

4.

Since HTML is hard coded into the Servlet code it is very difficult to support
i
n-
ternationalization
.

Internationalization is the ability to adapt the web page co
n
tent
to
the user’s locale.




I
ntroduction to JSP


Since, it became a
pparent that Servlets

are not very good

for

developing complex Web
interface the
JSP 0.92 specification

[60
]

was created.

JSP was introduced as a standard
t
emplating solution and was also promoted as the
M
odel
1 arch
i
tecture

[18]
.


Internally JSP technol
ogy is built on top of the
Servlet technology.


JSP and Servlet i
n-
ternal design is so
strongly
related that a JSP after
being
compiled by the container gets
translated into a Servlet and is later ex
e
cuted by the Servlet container.


Even though a

JSP

intern
al design is so similar to
Servlet

they still offer

a very different approach

to cre
ating
web interfaces
.

While Servlets are Java objects capable of generating markup, JSP pages
are markup components that permit escaping into Java as nece
s
sary to initiate

processing.


Again to make things cl
ear
we will

look at a simple example:


<%@ page language="java"

import = "examples.withoutframework.com.wrox.begjsp.ch03.*,java.util.*" %>


<%!

public

void

jspInit() {


getServletContext().setAttribute("cats", ES
hop.getCats());

}


public

void

jspDestroy() {


getServletContext().removeAttribute("cats");

}


private

String dispPrice( String price) {


int

len = price.length();


if

(len <= 2)


return

price;


else



return

"$" + price.substring(0,
len
-
2) + "." + price.substring(len
-
2);


-

22
-

}

%>


<html>

<head>

<title>Wrox Shopping Mall</title>

</head>

<body>

<table width="600">

<tr>

<td width="20%">

<%


ArrayList cats = (ArrayList) application.getAttribute("cats");


for

(
int

i=0; i< cats.size(); i+
+) {


Category curCat = (Category) cats.get(i);

%>

<a href="<%= request.getRequestURL() + "?catid=" + curCat.getId() %>">


<%= curCat.getName() %>

</a>

<br/>

<%


}

%>

</td>

<td>

<h1></h1>

<table border="1">

<tr><th align="left">Item</
th><th align="left">Price</th><th align="left">Order</th></tr>

<%


String selectedCat = request.getParameter("catid");


if

(selectedCat ==
null
)


selectedCat = "1";


ArrayList items = (ArrayList) EShop.getItems(selectedCat);

for

(
int

i=0; i< ite
ms.size(); i++) {


Product curItem = (Product) items.get(i);

%>

<tr>


<td><%= curItem.getName() %></td>


<td><%= dispPrice(String.valueOf(curItem.getPrice())) %></td>


<td><a href="<%= request.getContextPath() + "/example3/shopcart.jsp?action
=buy&sku=" + c
u-
rItem.getSku() %>">


<b>BUY</b></a>


</td>

</tr>


<%


}

%>


</table></td></tr></table></body></html>

Fragment
2


The above
JSP code after being translated by the JSP container is rendered by the
brow
s-
er

as show below
:



-

23
-



T
he above example is taken from Beginning Java Server Pages by Vivek Chopra, Jon
Evas, Rupert Jones, Sing Li and John T. Bell. Though the
example provided here ca
p-
tures

the essence of JSP technology and also provides a basis for discussi
on, it

is not a
refle
c
tion of a real world application
.

If you are interested in learning
more about

the

JSP

technol
ogy then please look at resources [4], [42] and [60] cited in the bibliography se
c-
tion.


Because JSPs look very much like HTML page
s

they we
re over
-
enthusiastically adopted
and th
is led

to
a host of new problems.

To
better understand the
s
e

problem
s

let

us

look
at
a simple J2EE web application architecture also called as JSP Model 1

[18]
.


In a JSP
Model 1 the HTTP requests are handled by JSPs
, which then creates domain objects from
t
he request parameters and passes

them to the business
logic layer
.

Each JSP then re
n-
ders the result of the business processing.

The JSP infrastructure makes it easy to impl
e-
ment this approach.

The following are
the features provided by this architecture:

i.

Automatically populate JavaBeans declared
in the page

with request parameter
values, using th
e <jsp:useBean> standard action

ii.

Access and manipulate
session, req
uest and application attributes

iii.

Scriplets to perform
any kind of logic


-

24
-

Short comings



Though
Model 1 or JSP

offers a very simple approach to web application development it
has the following disadvantages:


1.

Because of the use of scriplets JSP pages bear little resemblance to the markup

(HTML)

they generate.
This defeats the very point of using JSP pages.

This also
becomes evident when you at look at Fragment 2.


U
sing scripting elements within JSP is now a practice that is highly discou
r-
aged”

[42] (page 180).

2.

A false assumption that JSP is the only view techn
ology
.

This r
e
sulted

in making

the web interface too tightly coupled to JSP technology and
is not acceptable.


JSP is just one
of the
view
technologies

available to J2EE applications and there
are many other view technologies like XSLT,

Velocity, etc.

eac
h having a specific
use.

3.

Java
code in JSP
, that is the

scriptlets

are

hard to test and cannot be reused.

T
h
is
approach
is
not object
-
oriented

and

also fails to deliver

the basic

(method level)

code reuse.

As you can see in fragment 2
,

the

following script
let cannot be r
e
used
and unit tested

[40] (page 445)
.

<%


String selectedCat = request.getParameter("catid");


if

(selectedCat ==
null
)


selectedCat = "1";


ArrayList items = (ArrayList) EShop.getItems(selectedCat);

for

(
int

i=0; i< items.size(
); i++) {


Product curItem = (Product) items.get(i);

%>



4.

JSP pages will contain a mish
-
mash of markup and Java code, making them hard
to develop and maintain
for
both

Java
and

markup

developers
.

This becomes ev
i-
dent even when you

look

at a simple exa
mple like Fragment 2.

“Embedded Java code mixed with JSP is difficult to read and debug, and ther
e-
fore difficult to maintain”

[42] (page 180).

5.

Handling all the possible request paths is difficult and often results in complex
conditional logic or the need t
o forward to another JSP
.


T
his makes the applic
a-
tion workflow
difficult

to
understand and maintain
.


-

25
-

JSPs
do not promote reuse, they are not object oriented and above all they were never
meant to have control or application logic. The original intent and
the only intent of JSP
technology was to deal with the presentation logic and display data. Hence, a strict

one
line summary of the model 1

(JSP only

and not Servlets
)

arch
i
tecture discussion
will

be
that it results in
an
un
-
maintainable code and should ne
ver be used in real time applic
a-
tions

[40]
.



Finally, JSP is
a
very powerful technology, but its power creates
as
many

problems

as
it
solves
.

To give
you
an analogy
it
is like a double edged sword and hence should be used
very carefully.

To summarize,
J
SP pages are e
xcellent at displaying data but

ill
-
suited
for

r
e
quest processing and initiating business logic.


Thus far, we have briefly looked into the Servlet and JSP technology and discussed their
strengths and shortcomings. Now,
let’s

look into the ge
neral challenges

faced

by

web a
p-
pl
i
cation development (J2EE)

that are not faced by the traditional GUI applications

and
later see how the model view controller architecture

(MVC)

can help solve some of these
pro
b
lems
.


Challenges of web application develop
ment


Listed below are some of the challenges faced in web application deve
l
opment

using Java

which are not seen in the traditional GUI interfaces:

1.

Dynamic w
eb interfaces tend to have a lot of JavaScript, HTML, and cascading
style sheets (CSS)

[14] and

Web

applications

built using Java make
s

it more
complex by inserting scriplets

(java code enclosed within tags)

and tags ever
y
where in the code. This
make
s

the
JSP
pages less maintainable and
will

also i
n-
crease the development time because most good Java an
d J2EE developers are not
very good with HTML, JavaScript and CSS and same is true for web developers
as they are not very good with their OO and Java skills.

For details please look at
the JSP section.


-

26
-

2.

HTTP

promotes pull nature and the server can respond
or push data to a client o
n-
ly when the client specifically asks for it. This means that the

web interfaces

(built
using HTTP and
not
direct sockets)

cannot dynamically update the
m
selves with
changes in the model
as is done in traditional GUI based applicat
ions like Swing
.

This is not a concern but it makes web application design

different

from the
trad
i-
tional
GUI application design.

3.

HTTP supports only String type parameters, so this means that the
S
tring type p
a-
rameters passed from the view should be conver
ted to the appropriate Java types
before they are passed to the business

service

objects.

For instance to process a simple from like

shown below
:


<HTML>

<HEAD>

<TITLE>Add Product</TITLE>

</HEAD>

<BODY>

<form action="addProduct" method="post">

<h3>Add Prod
uct</h3>

<table>

<tr><td> Product Name: </td> <td> <input name="name"/> </td>
</tr>

<tr><td> Price: </td> <td> <input name="price" id="price"/>
</td> </tr>

<tr><td> Description: </td> <td> <input type="text"
name="productDescription"/> </td> </tr>

<tr><
td></td><td> <input type="submit" value="Save"/>
</td></tr>

</table>

</form>

</html>



Fragment
3


-

27
-


When rendered by the browser


You need the following processing

code:

public class AddProduct extends javax.servlet.http.HttpSe
rvlet implements javax.servlet.Servlet {



protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
Ser
v
letException, IOException {


String produtName = request.getParameter("name");

String productDescription = request.getParam
eter("productDescription");

String priceString = request.getParameter("productDescription");

double price = (priceString != null && !"".priceString)? Do
u
ble.parseDouble(priceString) : 0;

String manufacturingDateString = r
e
quest.getParameter("manufacturingD
ate");

DateFormat simpleDateFormatter = new SimpleDateFo
r
mat("MM/dd/yyyy");

Date manufacturingDate = (manufacturingDateString != null &&
!"".manufacturingDateString)

? simpleDateForma
t
ter.parse(manufacturingDateString) : null;


//some other logic

left for
brevity

}




//other methods left for brevity

}


Fragment
4


Supporting only String type parameters is not a limitation for the HTTP,
but in
fact

this is what gives

it the power to link two

different systems. This is more the
lim
itation of the Servlet

and JSP

model which forces you to
do this

mechanical

and time consuming (development time)

conversion every time

for every HTML
form in every pag
e of your application
.


-

28
-

4.

We have very limited control over the browser and this makes use
r input valid
a-
tion difficult. Hence,

no matter what we do on the client side (browser) we
will

again have to validate the parameters once they reach the server.

Lets again take Fragment 3 as an example and put a validation rule that states that
product na
me cannot be null. Below is the code to enforce that validation rule:

public class AddProduct extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
S
er
v
letException, IOException {


String produtName = request.getParameter("name");

If(
produtName

== null || “”.equals(
produtName
)){


throw new ValidationException(“Product name cannot be null or empty”);

}


//some other logic

left for brevity

}




//other m
ethods left for brevity

}

Fragment
5


This code looks generic but has to
be
written or at least invoked by every HTML
form in every page of your application, which is unnecessary work.

5.

Web interfaces built with Java make use of t
he container services

like the Servlet
and JSP container

and
this makes them

very hard to unit test.

For instance
,
the
EStore Servlet from fragment 1 cannot be tested until the web application server
is started, which takes time and slow
s

down the develop
-
test
-
debug

cycle and
leads to developer’s frustration.

6.

Every

browser has its own peculiar way of rendering the page

and also interpre
t-
ing and running the scripts. This makes development all the more difficult

[8, 10,
13]
.

7.

Security is also a challenge bec
ause a web application is accessible to anyone is
prone to many more attacks than a traditional client server application.

8.

The stateless nature of HTTP makes it difficult to maintain a user session.

The
HTTP specification states that
the
sockets

should be
flushed out and closed after
every communication (request
-
response)
. This means that HTTP lacks the cap
a-
bility to maintain client

state
over multiple requests which is
very
critical for web
applic
a
tions.


-

29
-


These challenges make it hard to develop a web appl
ication and even harder without sa
c-
rificing
object orientation
.


Need for
MVC


T
he
Servlet
-
only and
the JSP model 1 architecture
s

have

severe disadva
n
tages and
make

it impossible to achieve a separation of responsibility between Java d
e
veloper and
markup d
eveloper r
oles
. This

lack of separation in

responsibility is a major concern for

big companies and complex web sites
. This
demanded the need for the

introduction of
MVC architecture
t
o web applications
.

In the J2EE world it is often also r
e
ferred to as
th
e model 2 architecture

[18]
.

This architecture uses the
both the JSP and Servlet

tec
h-
nologies together, Servlets to handle control flow, and JSP pages or another view tec
h-
nology to render content and
this helps avoid

all the problems we have di
s
cussed

so
far
.


In simple words MVC is
an
architectural pattern
which
divides an intera
c
tive system into
three components,

which is

the
model data objects
,
the view
that present
s the

model data
on screen
and the controller
that react
s

to user input by updating mode
ls appropriately

[24,
53
,
44]
.


There is lot of liter
a
ture available on the MVC architecture which does a
very good job
of describing MVC in detail.

Hence,

we
will

not go any further into di
s-
cussing MVC

and rather

concentrate more
on how to adap
t MVC for
J2EE web applic
a-
tions, which is very different tha
n the MVC architecture for traditional
(GUI)
sy
s
tems.


In a traditional MVC architecture for GUIs each view registers with a model, which pu
b-
lishes events when its data is updated.

This is a push
model

tha
t

is

the model pushes not
i-
fications to any number of listeners, which are typically (but not necessarily) views.

This
is very different for web application because web applications are usually a pull mo
d
el

that is

the data is only displayed to the

user wh
en explicitly requested
.

Hence, it won't
help to register
the
view to receive ongoing notifications from the model.

The s
o
lution to
this pro
b
lem is to provide the view access to the model(s) required to render a dynamic
page.

The MVC architecture deli
v
e
rs its key benefits regardless of what model we use.


-

30
-

The main benefit of using MVC is

the division of the system into three well defined
comp
o
nents
.


In
a true
MVC architecture
,

models should not

contain any view
-
specific code.

V
iews
should not contain
any control code or data
-
access code and should just concentrate on
displaying data.

Controllers should create and update models and they should not depend
on any one particular view i
m
plementation.


MVC provides a lot of benefits to web application devel
opment
,

but at the same time it is
complex to implement

for web applications
.

This is perhaps the reason why web fram
e-
works
like Struts and JSF
are so helpful and popular.


Controller


The controller is central to MVC in a web application.

Below are its
key responsibilities:

1.

Handle the
HTTP
request along with its paramete
rs
.

2.

Validate the
HTTP
request parameters
.

3.

Create and populate the domain object

using the HTTP

request p
a
rameters
.

4.

Invoke
the business service

and

make

the domain object

available
.

5.

Catch
application exceptions resulting from business
service

invocations, modif
y-
ing model creation, and view selection accordingly.

6.

In applications with server
-
side state, to create and manipulate se
s
sion state
.

7.

Choose a view an
d cause it to render by making th
e

domain objects

available
.


As you can see t
he aforementioned
responsibilities
are

an intermingling

of

business logic
and plumbing code.

Hence, i
t is the responsibility of any

good web application
fram
e-
work
to

help separate

the plumbing code from busines
s logic
.





-

31
-

Model (or) Domain Objects


In enterprise
application development jargon

the model is often referred to as domain o
b-
jects. M
odel

or domain objects contain

data displayed by a view.


In
a

J2EE web applic
a-
tion, the model normally consists of Java

Beans

[12]

though it does not have to be

so
.


In
a typical application
,

d
o
main objects are nothing but value objects which hold data but do
not pr
o
vide any functionality.

Domain objects are used by the
service

objects to perform
the business logic and
ar
e later provided to the view

[37,
39]
, typically by setting it in the
request or session scope.

The view then

u
p
dates itself according to the
values provided
by the domain objects
.



The domain object should not perform any data access, a
s this should be
handled
by the
service

objects
or data access object (DAO)
.

There is also no reason for a model to d
e-
pend on the Servlet API or a web appl
i
cation framework
because

doing so
will

make
them u
nu
sable outside the web tier

and also make testing difficult
.


Vi
ew


A view is responsible for displaying the information contained in the model.

In a good
MVC implementation a view does not have to know

anything

about the controller or the
business
logic

implementation.

Cu
r
rently, JSP is the most

widely

used view tec
hnology
for J2EE applications, although there are several other
s

available.


Below are the best practices for the view components implementation:

i.

It should be wholly respons
ible for generating the mark up
.

ii.

It should not
intercept or handle the request
.

iii.

It
should not perform any data
access or invoke business logic
.

iv.

It should not have to de
al with
business logic or data
-
retrieval e
x
ceptions
.

v.

It should be possible to seamle
ssly change the view and also the view technology
being used
.



-

32
-

A view’s essential respo
nsibility is to just display the data and this pr
o
vides us with the

f
lexibility to substitute a view with another or in fact change the view technology without
affecting the working of the applic
a
tion.

Giving the view component such limited and
c
learly de
fined respo
n
sibilities is the best way to ensure the separation between the roles

of Java developers and web developers.

This

also simplifies testing

to a great extent

b
e-
cause now we just

need
to
perform

our regression and unit

tests

on the controller

and

the
business logic

because
we know that
the view does not have any logic in it.



























-

33
-

Chapter
3


Discussion on Struts and JSF


The difficulties and problems associated with using raw JSP and Servlet technologies
demanded the need for a

web framework.

Since, J2EE is the most popular enterprise
technology among open source developers
,

there is plethora of web frameworks available
today
,

with Struts and JSF being the most popular one
s
.

This wide array of options
makes
it very difficult t
o choose one framework
.


In this chapter
, I will

briefly talk about the design of Struts and JSF

and later give a brief
comparison of these frameworks
.

Since, the primary goal of this starred paper is to
di
s-
cuss

J2EE

web application development in a
n empi
rical and

concise
way;

I
will
not be
going into the details of either of these frameworks.

Pleas
e

refer to the bibliography se
c-
tion to learn more about these frameworks.


An example application


Web store


To demonstrate the use of these frameworks and
to highlight their problems we would
use

web

store
,

as an example application
.
T
he sole
intent

of this

application is to
pr
o
vide
a basis to discuss these
frameworks
. Hence,

it
has intentionally been kept very simple.
B
e
low

are
its

requirements
:

Requirement
s

1.

The user visits the application
and
is asked for authentica
tion. If authorized, the
user enters the web store

and
browses the

list of products available in

his

area of
residence

(same zip code)
.

2.

The user
browse
s
the

complete

products list (not filtered b
y zip code)
.

3.

The
user selects a product from the list and views

its details.

4.

The user add
s

a product to the catalog.



-

34
-

5.

The system should ensure that a single user cannot add more than 5 items in one
week.

6.

The system should
also
ensure that the product name

should be in between 3 and
20 characters and its price in no greater than 5500.


As you can see this application’s functionality is very limited and does not reflect a real
world online web store. However it suffices to discuss
the

frameworks referred in
this
p
a
per.


Note:
We would not be implementing
all the use cases for

each framework
,

but would rather pick pieces
(use cases) of it to demonstrate things as and when necessary.
Though

all the use cases

will be fully impl
e-
mented using
the framework

develop
ed in this paper

and
code for it
can
be

found in the distribution pac
k-
age.


Note:

The framework does not have a persistent store and all its data is stored in the main memory.

The
framework also does not
use

any encryption, active directories, etc. to impl
ement security.



Struts


Until recently Struts was a de
-
facto standard for J2EE

web application development.

Struts

is a
n

MVC based framework for J2EE web applic
a
tion development, available for
download from the prestigious open source house of Apache.

It was initially developed
by Craig R
McClanahan

the main developer for the Tomcat Servlet engine and was d
o-
nated to the Apache foundation in the year 2000.

Since
,

its inception Struts
has
e
n
joyed
an acceptance and growth rate as never seen before.

The f
ollowing are the reasons for its
stupendous success:

i.

F
irst MVC framework to be developed for J2EE web applications.

ii.

F
airly simple to learn and use.



Struts Design


The struts framework was originally divided into eight top level packages namely Action,
Ac
tions, Util, Tiles, Config, Upload, Taglib and Validator.

Each package
contains

cla
s-

-

35
-

ses with clearly d
efined responsibility. The

idea

is

that these responsibilities should not
cross over the packages.

However, the responsibilities do cross over the packa
ges and
people have

also

found some

circular dependencies between the packages.


To better understand the design of the framework lets look at the sequence diagram for a
typical user request

(
taken from the
struts documentation
)
:



Figure
2
:
Request handling and processing in Struts



Message Description


1.

The client submits a
n

HTML form using the HTTP post, and in r
e
sponse to that the
ActionServlet’s doPost method is called to handle the request.


-

36
-

1.1.

ActionServlet delegates to RequestP
rocessor by calling the process method to
handle the request.

1.1.1.

RequestProcessor retrieves and creates the ActionForm bean associated
with the request, if it does not already exist in the session scope.


1.1.2.

Populates the ActionForm bean with the HTTP request p
a
rameters

1.1.3.

Validates the HTTP request parameters errors and creates ActionError o
b-
jects for each validation error.

1.1.4.

Acquires the application specific Action subclass instance and calls the
execute method to process the request.

1.1.4.1.

Retrieves data from the UserAc
tionForm bean by getProperties
met
h
ods

1.1.4.2.

Calls business services through the Busines
s
Delegate

1.1.4.3.

Populates a value object bean (optional)

1.1.4.4.

Forwards to the specified destination in struts
-
config.xml by r
e-
turning the ActionMapping o
b
ject

2.

The JSP constructs the vie
w by getting data from the HelperBean or value object.

3.

JSP also gets the properties from ActionForm.



The main components or objects of the struts framework are described b
e
low:


Action Servlet:


This class forms the core of the Struts framework.


It is a
n implement
a-
tion of the F
ront
Controller pattern described in the Core J2EE patterns catalog and has
the responsibility to map the action events
that is the

HTTP request to action classes on
the server side based on a XML configuration file called the stuts
-
config.xml.

This class
is responsible for the creating an instance of Action, ActionForm and ActionForward o
b-
ject based on the values spec
ified in the configuration file
.

The ActionForm and Actio
n-
Forward o
b
jects are created for each request but the Acti
on objects are singletons.


Action:


This serves as a wrapper to the business logic.

This serves
is
the best place to do
things like auditing, authorization, etc.

In
other words, it is
used as an extension to the
controller.



-

37
-

ActionForward:


An Action ob
ject on invocation of
its

execute

method returns the A
c-
tionForward object.

This determines which JSP or Servlet the request has to be fo
r
war
d-
ed to.

In other words
,

the ActionForward class represents a logical abstraction of a web
r
e
source.


ActionForm:


Holds the request parameters for the current HTTP request.

It is an a
b-
stract class which has to be sub
-
classed for each HTML form.

The ActionContro
l
le
r-
Ser
v
let creates and populates this object and then passes it to the ActionClass for each
HTTPR
e
quest.


ActionError:


An ActionError object holds the error information generated while bin
d
ing
the request parameters to the ActionForm object and also if the call to the validate met
h-
od does not succeed.


ActionErrors:


ActionErrors as the name suggests is a co
llection of A
c
tionError objects.

These errors are displayed to the user with the help of custom tags.


ActionMapping:


An ActionMapping object holds the mapping of HTTP requests to the
Action objects.

It is an object oriented representation of the inform
ation contained in the
struts
-
config.xml file.


ActionMappings:


As the name suggests this is a collection of ActionMa
p
ping objects.


Stuts
-
config.xml:


Defines the work flow for the application.

It maps the HTTP r
e
quests
to the Action objects, maps the
Action to the ActionForm objects, specifies the Actio
n-
Forward for the Action, specifies a
n

error handler for the request,

global error
handler
,

a
section to define external plug
-
ins, etc.


In other words
,

this is the heart of