Sunteți pe pagina 1din 32

The Emperor Has New Clothes: Is J2EE Changing?

By Kanbay’s Shared Architecture Services Group


July 2004

PURPOSE A detailed comparison indicates that


The article is first in a series intended to Spring MVC has significant advantages
generate awareness about the evolving such as interface based design, trans-
J2EE trend of compositional, lightweight parent integration with middleware ser-
containers and their impact on J2EE ap- vices and view independence. Addition-
plication development. The document is ally a detailed parametric analysis also
an initial discussion draft and the ideas points to the fact that Spring may have
expressed here are meant to initiate more flexible request processing, easier
discussion on the subject. configuration, better performance and
better support for transactions and se-
curity. This however will need to be bal-
SUMMARY anced against standards compliance and
The document starts by analyzing the an established market base.
current J2EE application development
The article concludes by making certain
space and the prevalent architectures
recommendations about the use of
and development approaches are
Spring framework.
elaborated. The study argues that the
problems with the enterprise java bean This is the first in a planned series of
specification, emergence of composi- three such articles which compare light-
tional architectures based on several weight practices and frameworks with
open source architectures as factors the current recommended J2EE prac-
leading to the emergence of the parallel tices. We start the series by comparing
non-specification oriented thinking to- Spring MVC implementation with Jakarta
wards aspects and lightweight contain- Struts project, the most widely used
ers as the newer paradigms in the J2EE J2EE framework.
application space

Lightweight frameworks are defined as INTENDED AUDIENCE


context independent, compositional
This document is intended for use within
framework that support object oriented
Kanbay. While we make our best effort
design. The two key patterns found in
to be correct, the information is based
the implementation of these compo-
on available public domain information.
nents are Inversion of Control which
We intend to continue to evolve this
6400 Shafer Court allow easy composition and Aspect Ori-
analysis through demonstration based
Rosemont, Illinois 60018 ented Programming which allows trans-
approaches.
parent access to middleware services.
847 384 6100 Spring—a lightweight framework is
847 384 0500 fax thereafter described and the MVC im-
plementation provided with the Spring
©2004 Kanbay Incorporated. All
rights reserved. Kanbay and the Framework is compared with the market
Kanbay logo are trademarks of leading Struts Framework which is the
Kanbay Incorporated. Other
trademarks are the property of current de-facto standard.
their respective owners.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 1: Component, Container & Services Model mission critical, highly available,
transactional enterprise systems. Each
application server vendor adds features
such as high performance cluster aware
caches, failover and load balancing
support for the application. EJB
containers have evolved to become
highly complex and heavyweight
middleware components.

Application Architectures
The application development using J2EE
framework use a standard set of com-
ponents. Servlets are the primary web
components with Java Server Pages
forming the primary view tier. The com-
ponents are hosted within the web con-
tainer.
Table of Contents
Purpose............................1 Enterprise Java Beans are the primary
Summary..........................1
business and persistence implementa-
Intended Audience..............1
J2EE PRACTICE tion. Message Driven Beans provide
J2EE Practice.....................2
Web Only Architecture and The mainstream J2EE application devel- asynchronous access to services devel-
Light Weight Containers. .4
opment is based on the use of oped as part of the container.
Lightweight Containers
standards compliant infrastructure
Implementation.............5 The enterprise java bean could be dis-
Aspect Oriented Programming designed to develop highly distributed,
tributed or collocated and provide both
...................................6 large scale, enterprise class application.
remote and local interfaces for the pur-
Spring Lightweight Container
...................................7 J2EE uses the component, container pose.
Web MVC..........................9
and services platform model with
Participants & Responsibilities Additionally POJO’s (plain old java ob-
containers managing component life
...................................9 jects) are used across all tiers for data
Features of Spring MVC.....10 cycle and providing services required for
transfer and correlation between differ-
Struts.............................12 the distributed applications such as
ent tiers.
Struts Features.................14 naming and location, declarative
Comparing Spring with Struts
transaction security etc. Both a fully distributed multi-JVM de-
.................................15
Request Processing ployment and single JVM deployments
The primary idea behind the separation
Architecture.................17 with collocated web and EJB containers
Configuration...................17 is to ease application development
is widely used.
View...............................18 where the application programmers
Security Model.................18 could focus on developing business logic Exhibit 2 illustrates the commonly used
Transaction......................18
while container provides easy access to architectures.
Validations and Error
6400 Shafer Court services necessary for distributed appli-
Handling.....................19
Rosemont, Illinois 60018
Performance....................19 cation development. The containers are
Application Development
Community Acceptance.....20 required to support a certain minimum
847 IDE
384 6100
Support.....................21 set of services for compliance to an The J2EE application development lead
847 Conclusions.....................21
384 0500 fax evolving set of J2EE standard. The cur- to a common set of challenges and pro-
References.......................22
rent specifications require supporting a ductivity of application development has
About the Authors.............22
©2004 Kanbay Incorporated. All
large set of services as shown in the been a major challenge since the speci-
rightsAppendix
reserved.A:Kanbay
List of and the
open-
Kanbay logo are trademarks of attached diagram. fication began to be used on large scale
source MVC frameworks 23
Kanbay Incorporated. Other
Appendix
trademarks areB:
theSome Issues
property of
applications.
their respective
with EJBowners.
Specification....25 The EJB containers also need to address
architectural qualities necessary for

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 2: Commonly Used Architectures

Over a period of time several patterns business specific services or compo-


have evolved as best practices. Arguably nents.
some of these patterns are attempts to
workaround the limitations of the The ability to compose solutions through
specification or implementation of J2EE the use of available components,
technologies and have gone from the frameworks and micro-architecture
status of being patterns to anti-pat- therefore is a significant part of applica-
terns. A number of micro architectures tion development today and is important
which are a combination of the J2EE to achieve productivity.
patterns are widely used.
Specification Resistance
Two architectural styles that have been “As components of application server
very widely used in J2EE applications technology, J2EE and Enterprise Java-
include Layers and Model View Con- Beans (EJB) are not the same thing.
troller (subject of this article). Most Java projects use Java Server
Pages (JSP)/servlet capabilities and not
6400 Shafer Court A large number of both open source and
EJB. Higher-priced application servers
Rosemont, Illinois 60018 proprietary frameworks are available
are designed to run EJB, yet they are
whose implementations are based on
using JSP/servlet capabilities instead.”
847 384 6100 the current known best practices while
847 384 0500 fax some other become the source for some “Companies have overspent about $1
new patterns. billion on application server technology
©2004 Kanbay Incorporated. All
rights reserved. Kanbay and the solutions since 1998. Moreover, an ad-
Kanbay logo are trademarks of Today application development involves
Kanbay Incorporated. Other ditional $2 billion may be wasted be-
identification of application patterns,
trademarks are the property of tween now and 2003.”
their respective owners. provisioning and composition of appro-
priate frameworks and development of

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


“Don't let confusion or hype push you to performance, poor EQL capabilities,
spend more than necessary.” poorly designed O/R mappings and a
whole host of other issues.
Gartner Group
 EJB’s subverted good object ori-
J2EE application development and im- ented designs as the limitation of
plementation has generally been com- the technology dictated design
plex and software development commu- choices e.g. EJB’s provide no easy
nity has struggled with improving devel- way to implement several patterns
opment and maintenance productivity. such as Singleton or the fact that a
number of J2EE patterns are designed
The Enterprise Java Bean component to provide workaround to these prob-
model however has several weaknesses lems were developed as part of the
and has been slow in evolving. Some J2EE specification. e.g.. Value Ob-
difficulties with the EJB specification jects, Fast Lane Reader, Composite
are(1)— Entity etc.

 Complex set of interfaces and classes Problems with the specification have
required to implement EJB compo- lead to widespread evolution of non-
nents and a programming model that standard specifications and adoption of
requires external (non-compiler) con- architectures that use alternatives to the
sistency management. Enterprise Java Beans in both the busi-
ness and persistence management tiers.
 Careful design requirements to
The most noticeable such efforts being
achieve adequate performance for
evolution of Aspects as an alternative to
remote calls.
components allowing use of POJOs as
 The introduction of local interfaces business objects and development of
was intended to address performance persistence frameworks such as Hiber-
due to remote references. However nate.
the semantic differences (call by value
vs. call by reference) prevented Some of these changes have also
seamless migration from local to re- started to influence the specification and
mote interfaces. EJB 3.0 is likely to adapt some of these
changes.
 The use of separate local and. remote
interfaces impacts location transpar-
ency Web Only Architectures
Alternative architectures that avoid use
 The need to use JNDI lookup, use of
of Enterprise Java Beans completely and
home interfaces and need to throw
used only the web container have be-
remote exception made the client de-
come increasingly common and are be-
pendent on EJB API or required the
ing applied to a large class of applica-
client to implement business dele-
tions. These are combined with web
gates which hides API complexity but
6400 Shafer Court server based load balancing to increase
Rosemont, Illinois 60018 leads to code redundancy
service capacity thresholds. See Exhibit
 Testability of applications developed 3.
847 384 6100 with Enterprise Java Beans outside
847 384 0500 fax the container
WEB ONLY ARCHITECTURE AND
©2004 Kanbay Incorporated. All  Entity beans for data access proved LIGHT WEIGHT CONTAINERS
rights reserved. Kanbay and the
Kanbay logo are trademarks of very unsatisfactory because of poor
Kanbay Incorporated. Other The web only architectures though ele-
trademarks are the property of
their respective owners.
gant lacked container support for dy-
1
Note : For a full list of issues with Enterprise namic discovery, lifecycle management,
Java Beans refer to Appendix B.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 3: Web Only Architectures Provide their own layer to simplify de-
velopment and allow declarative binding
of objects

 Some provide capabilities such as de-


clarative transaction handling.
 Allow the component to be embedded
in any context and are platform ag-
nostic where they can be deployed on
an existing J2EE platform
 Allow the core object model to be pre-
served through the implementation
unlike the EJB models
 Do not normally support capabilities
such as cache management and
cluster aware application objects
pooling, declarative transactions and Some examples in this category include
clustering middleware services available Pico Container, HiveMind and Spring
through the EJB container. which is the most popular and mature
lightweight container.
This is an area which has attracted a lot
of attention recently and has lead to the Some micro-kernels based application
emergence of several new techniques. servers such as JBoss support similar
Aspect Oriented Programming has re- capabilities underneath their J2EE serv-
cently gained a lot of momentum in the ers. Although originally intended as in-
J2EE community. frastructural components for a layer
below the application servers, some
A category of products called light-
vendors are beginning to expose their
weight containers represents the con-
microkernel as lightweight containers for
vergence of the trends identified earlier
direct use by application developers.
in the article namely compositional na-
ture of the application development,
large number of open source projects LIGHTWEIGHT CONTAINERS
and attrition from EJB’s. Although no IMPLEMENTATION
standard definition exists for the light-
Lightweight containers usually are based
weight containers category, for the pur-
on the notion of Inversion of Control to
pose of this document we define light-
allow composition of components and
weight containers as containers that—
support Aspect Oriented Programming
to provide several of the transparent
 Are mostly compositional and do not
middleware services such as declarative
include a lot of behavior, other that
6400 Shafer Court transactions, security and logging.
allowing classes to be plugged to-
Rosemont, Illinois 60018
gether. They help to assemble com-
ponents from different projects into a Inversion of Control or Dependency
847 384 6100
cohesive application. Injection
847 384 0500 fax
Inversion of Control (IoC) is a design
 Do not use EJB’s as component model
©2004 Kanbay Incorporated. All pattern that helps to reduce coupling
rights reserved. Kanbay and the but rather use lightweight model such
and dependencies between components.
Kanbay logo are trademarks of as POJOs, MBeans or some simpler
Kanbay Incorporated. Other In general, IoC is a principle that sepa-
trademarks are the property of component model.
their respective owners. rates an API from a framework, and is
based on who is “in control”. The word

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 5: Web Only Architectures

“inversion” from the pattern name refers The container creates all the objects,
to inverting the “normal” way in which wires them together by setting the nec-
components obtain references to each essary properties, and determines when
other. methods are invoked.

This principle can be illustrated by ex- The main process of Inversion of Control
ample through the difference between is illustrated by the diagram in Exhibit 5.
an IoC framework and a class library.
More recently, this concept has been
The major difference between an IoC renamed Dependency Injection. The
framework and a class library is that the article by Martin Fowler provides a de-
framework calls the application code, tailed explanation of the concept.
whereas normally the application code
would call the class library. This principle As shown in Exhibit 4, there are three
is also referred to as the Hollywood different implementation pattern types
Principle, (“Don’t call us, we call you!”) for IoC.

In lightweight containers that use this


principal of inversion of control you ASPECT ORIENTED PROGRAMMING
don't create our objects, you describe Some lightweight frameworks use im-
how they should be created. You don't plementation of Aspect Oriented Pro-
directly connect your components and gramming to further improve on their
services together in code, you describe support for transparent middleware ser-
which services are needed by which vices such as declarative transactions on
components, and the container is re- POJOs.
sponsible for hooking it all together.

Exhibit 4: Implementation Pattern Types


6400 Shafer Court Source: Avalon Project
Rosemont, Illinois 60018
Interface Injection Services need to implement a dedicated interface through which
they are provided with an object from which they can look up de-
847 384 6100
pendencies (other services). This is the pattern used by the earlier
847 384 0500 fax
containers provided by Avalon.
©2004 Kanbay Incorporated. All Setter Injection Services dependencies upon are assigned via JavaBeans properties
rights reserved. Kanbay and the
Kanbay logo are trademarks of (setter methods). Both HiveMind and Spring use this approach.
Kanbay Incorporated. Other
trademarks are the property of Constructor Injection Services dependencies are provided as constructor parameters (and
their respective owners. are not exposed as JavaBeans properties). This is the exclusive ap-
proach

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Aspect Oriented Programming is in- Design Intent
tended to address requirements that do The Spring design goals as stated by
not decompose neatly into behavior Rod Johnson—
centered around a single locus. AOP is
based on the idea of programming by  Make J2EE easier to use or address
externalizing the crosscutting concerns the productivity challenge
of the system, describing the cross cut-
 Address end-to-end requirements
ting concerns and then using the AOP
rather than one tier
system to weave or compose them to-
gether into a coherent program. Aspects  Eliminate need for middle tier “glue”
can range from high-level notions like or support composition
security and quality of service to low-  Provide the best Inversion of Control
level notions such as caching and buff- solution as the strategy to implement
ering. They can be functional, like fea- easy composition
tures or business rules, or nonfunctional
(systemic), such as synchronization and  Provide a pure Java AOP implementa-
transaction management. tion, focused on solving common
problems in J2EE
AOP is focused on mechanisms for sim-  Fully portable across application serv-
plifying the realization of such crosscut- ers
ting concerns. Aspectual requirements
are concerns that (for common struc-
Overview
tural decompositions) introduce cross-
Spring contains a lot of functionality and
cutting in the implementation.
features, which are well-organized in
Aspects are beginning to replace the seven modules shown in Exhibit 6. This
Enterprise Java Bean component models section discusses each of the modules in
as the way of non-intrusively weaving turn.
middleware services to POJO based
The Core package is the most funda-
business objects. The EJB 3.0 specifica-
mental part of the framework and pro-
tion is making a tentative move the di-
vides the Dependency Injection features
rection
allowing you to manage bean container
functionality. The basic concept here is
SPRING LIGHTWEIGHT CONTAINER the BeanFactory, which provides a fac-
tory pattern removing the need for pro-
In this document we explore Spring the
grammatic singletons and allowing you
current leader in the implementation of
to decouple the configuration and speci-
the lightweight container. The container
fication of dependencies from your ac-
provides compositional capabilities as
tual program logic.
well as a number of packages that pro-
vide capabilities corresponding to differ-
On top of the Core package sits the
ent tiers in the application stack as an
6400 Shafer Court Context package, providing a way to
integrated consistent solution.
Rosemont, Illinois 60018 access beans in a framework-style man-
ner, that somewhat resembles a JNDI-
In this series of articles we explore the
847 384 6100 registry. The context package inherits its
MVC framework, business object imple-
847 384 0500 fax features from the beans package and
mentation and persistence capabilities of
adds support for text messaging using
©2004 Kanbay Incorporated. All the Spring framework and compare it
e.g. resource bundles, event-propaga-
rights reserved. Kanbay and the with current practice
Kanbay logo are trademarks of tion, resource-loading and transparent
Kanbay Incorporated. Other
trademarks are the property of creation of contexts by, for example, a
their respective owners.
servlet container.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 6: Overview of the Spring Framework

The DAO package provides a JDBC-ab- havioral information into your code, a
straction layer that removes the need to little like .NET attributes.
do tedious JDBC coding and parsing of
database-vendor specific error codes. Spring's Web package provides basic
Also, the JDBC package provides a way web-oriented integration features, such
to do programmatic as well as declara- as multipart functionality, initialization of
tive transaction management, not only contexts using servlet listeners and a
for classes implementing special inter- web-oriented application context. When
faces, but for all your POJOs (plain old using Spring together with WebWork or
java objects). Struts, this is the package to integrate
with.
The ORM package provides integration
layers for popular object-relational Spring's Web MVC package provides a
mapping APIs, including JDO, Hibernate Model-View-Controller implementation
and iBatis. Using the ORM package you for web-applications. Spring's MVC im-
can use all those O/R-Mappers in com- plementation is not just any implemen-
bination with all the other features tation, it provides a clean separation
Spring offers, like simple declarative between domain model code and web
transaction management mentioned forms and allows you to use all the
before. other features of the Spring Framework
6400 Shafer Court like validation.
Rosemont, Illinois 60018 Spring's AOP package provides an Aop
Alliance compliant aspect-oriented pro- Spring Web MVC and Struts
847 384 6100 gramming implementing allowing you to As explained above Spring addresses all
847 384 0500 fax define, for example, method-intercep- tiers of the web application. In the sec-
tors and pointcuts to cleanly decouple tion that follows we compare Spring’s
©2004 Kanbay Incorporated. All
rights reserved. Kanbay and the code implementing functionality that implementation of the MVC framework
Kanbay logo are trademarks of
Kanbay Incorporated. Other should logically speaking be separated. with the current market leader Struts.
trademarks are the property of Using source-level metadata functional- As Spring is a scalable system using
their respective owners.
ity you can incorporate all kinds of be- Spring allows a common set of infra-

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 7: Interactive Between Model, View & Controller Objects

structure classes to be used across tiers user interaction model. However, it is


of the application. straightforward to map these concepts
into the domain of multi-tier enterprise
applications.
WEB MVC
In the following section we describe  Model—The model represents enter-
MVC, Spring MVC and Struts (the most prise data and the business rules that
widely used MVC framework) and com- govern access to and updates of this
pare the two on a series of parameters data. Often the model serves as a
software approximation to a real-
The Pattern world process, so simple real-world
modeling techniques apply when de-
Model-View-Controller (MVC) architec-
fining the model.
ture separates core business model
functionality from the presentation and  View—The view renders the contents
control logic. Such separation allows of a model. It accesses enterprise
multiple views to share the same enter- data through the model and specifies
prise data model, which makes sup- how that data should be presented. It
6400 Shafer Court porting multiple clients easier to imple- is the view's responsibility to maintain
Rosemont, Illinois 60018 ment, test, and maintain. consistency in its presentation when
the model changes. This can be
847 384 6100 achieved by using a push model,
847 384 0500 fax PARTICIPANTS & where the view registers itself with
RESPONSIBILITIES the model for change notifications, or
©2004 Kanbay Incorporated. All
rights reserved. Kanbay and the The MVC architecture has its roots in a pull model, where the view is re-
Kanbay logo are trademarks of
Kanbay Incorporated. Other
Smalltalk, where it was originally ap- sponsible for calling the model when
trademarks are the property of plied to map the traditional input, proc- it needs to retrieve the most current
their respective owners.
essing, and output tasks to the graphical data.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


 Controller—The controller translates often preferable to bind directly to your
interactions with the view into actions business objects. This is another major
to be performed by the model. In a difference to Struts which is built around
stand-alone GUI client, user interac- required base classes like Action and
tions could be button clicks or menu ActionForm—for every type of action.
selections, whereas in a Web applica-
tion, they appear as GET and POST Spring has differentiated object roles: It
HTTP requests. The actions performed supports the notion of a Controller, an
by the model include activating busi- optional command or form object, and a
ness processes or changing the state model that gets passed to the view. The
of the model. Based on the user in- model will normally include the com-
teractions and the outcome of the mand or form object but also arbitrary
model actions, the controller responds reference data.
by selecting an appropriate view.
Regarding views: Spring's view resolu-
tion is extremely flexible. A Controller
Introduction to the Spring Web
implementation can even write a view
Framework
directly to the response, returning null
Spring's web framework is designed as ModelAndView. In the normal case, a
around a DispatcherServlet that dis- ModelAndView instance consists of a
patches requests to handlers, with con- view name and a model Map, containing
figurable handler mappings, view reso- bean names and corresponding objects
lution, locale and theme resolution as (like a command or form, reference
well support for upload files. The default data, etc). View name resolution is
handler is a very simple Controller in- highly configurable, either via bean
terface, just offering a ModelAndView names, via a properties file, or via your
handleRequest(request, response) own ViewResolver implementation. The
method. This can already be used for abstract model Map allows for complete
application controllers, but you will pre- abstraction of the view technology,
fer the included implementation hierar- without any hassle: Be it JSP, Velocity,
chy, consisting of for example Ab- or anything else—every renderer can be
stractController, AbstractCommandCon- integrated directly. The model Map sim-
troller and SimpleFormController. Appli- ply gets transformed into an appropriate
cation controllers will typically be sub- format, like JSP request attributes or a
classes of those. Note that you can Velocity template model.
choose an appropriate base class: If you
don't have a form, you don't need a
FormController. This is a major differ- FEATURES OF SPRING MVC
ence to Struts. If just focusing on the web support,
some of the Spring's unique features are
Any object as command or form object:

There's no need to implement an inter-
6400 Shafer Court face or derive from a base class.  Clear separation of roles: controller
Rosemont, Illinois 60018 Spring's data binding is highly flexible, vs. validator vs. command object vs.
e.g. it treats type mismatches as vali- form object vs. model object, Dis-
847 384 6100 dation errors that can be evaluated by patcherServlet vs. handler mapping
847 384 0500 fax the application, not as system errors. So vs. view resolver, etc.
you don't need to duplicate your busi-
©2004 Kanbay Incorporated. All
ness objects' properties as Strings in  Powerful and straightforward configu-
rights reserved. Kanbay and the
Kanbay logo are trademarks of your form objects, just to be able to ration of both framework and applica-
Kanbay Incorporated. Other
trademarks are the property of handle invalid submissions, or to con- tion classes as JavaBeans, including
their respective owners.
vert the Strings properly. Instead, it's easy in-between referencing via an
application context, e.g. from web

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


controllers to business objects and through IoC based context configura-
valuators. tion.
 Adaptability, non-intrusiveness: Use
When a DispatcherServlet is setup for
whatever Controller subclass you
use and a request comes in for that
need (plain, command, form, wizard,
specific DispatcherServlet it starts proc-
multi action, or a custom one) for a
essing it. The list below describes the
given scenario instead of deriving
complete process a request goes
from Action/ActionForm for every-
through if a DispatcherServlet is sup-
thing.
posed to handle it—
 Reusable business code, no need for
duplication: You can use existing 1. The WebApplicationContext is
business objects as command or form searched for and bound in the re-
objects instead of mirroring them in quest as an attribute in order for
special ActionForm subclasses. controller and other elements in the
chain of process to use it. It is
 Customizable binding and validation:
bound by default under the key Dis-
type mismatches as application-level
patcherServlet.WEB_APPLICATION_
validation errors that keep the of-
CONTEXT_ATTRIBUTE
fending value, localized date and
number binding, etc instead of String- 2. The locale resolver is bound to the
only form objects with manual parsing request to let elements in the chain
and conversion to business objects. resolve the locale to use when proc-
 Customizable handler mapping, cus- essing the request (rendering the
tomizable view resolution: flexible view, preparing data, etcetera). If
model transfer via name/value Map, you don't use the resolver, it won't
handler mapping and view resolution affect anything, so if you don't need
strategies from simple to sophisti- locale resolving, just don't bother
cated instead of one single way.
3. The theme resolver is bound to the
 Customizable locale and theme request to let e.g. views determine
resolution support for JSPs with and which theme to use (if you don't
without Spring tag library, support for needs themes, don't bother, the re-
JSTL, support for Velocity without the solver is just bound and does not
need for extra bridges, etc. affect anything if you don't use it)
 Simple but powerful tag library that
avoids HTML generation at any cost, 4. If a multipart resolver is specified,
allowing for maximum flexibility in the request is inspected for multi-
terms of markup code. parts and if so, it is wrapped in a
MultipartHttpServletRequest for
further processing by other ele-
Spring Request Processing
ments in the chain (more informa-
Spring's web framework is a request tion about multipart handling is pro-
6400 Shafer Court
driven web framework, designed around vided below)
Rosemont, Illinois 60018
a servlet that dispatches requests to
847 384 6100 controllers and offers other functionality 5. An appropriate handler is searched
847 384 0500 fax facilitating the development of web ap- for. If a handler is found, it execu-
plications. Spring's DispatcherServlet tion chain associated to the handler
©2004 Kanbay Incorporated. All however, does more than just that. It is (preprocessors, postprocessors,
rights reserved. Kanbay and the
Kanbay logo are trademarks of completely integrated with the Spring controllers) will be executed in order
Kanbay Incorporated. Other
trademarks are the property of
ApplicationContext and allows you to to prepare a model
their respective owners. use every other feature Spring has

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 8: Class Diagram

6. If a model is returned, the view is STRUTS


rendered, using the view resolver Struts is a set of cooperating classes,
that has been configured with the servlets, and JSP tags that make up a
WebApplicationContext. If no model reusable MVC 2 design. This definition
was returned (which could be the implies that Struts is a framework,
result of a pre- or postprocessor in- rather than a library, but Struts also
tercepting the request because of contains an extensive tag library and
for instance security reasons), no utility classes that work independently
view is rendered as well, since the of the framework.
request could already have been
fulfilled The following content is based on the on
an article by Jean-Michel Garnier in the
Exception that might be thrown during http://rollerjm.free.fr web site. Copy-
processing of the request get picked up right (c) 1999-2002 The Apache Soft-
by any of the handlerexception resolvers ware Foundation. All rights reserved.
6400 Shafer Court
that are declared in the WebApplica-
Rosemont, Illinois 60018
tionContext. Custom behavior can be
Struts MVC Implementation
847 384 6100 defined using exception resolvers.
The components in a Struts implemen-
847 384 0500 fax
Spring's DispatcherServlet can be cus- tation include Struts.xml which is a con-
©2004 Kanbay Incorporated. All tomized by adding context parameters figuration resource file parsed by the
rights reserved. Kanbay and the
in the web.xml file or servlet init pa- Struts Controller for initialization.
Kanbay logo are trademarks of
Kanbay Incorporated. Other rameters.
trademarks are the property of
their respective owners.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Class Diagram Since Struts 1.1, the processing logic
The major classes in the implementation has been delegated to the RequestProc-
are explained in Exhibit 8. essor class—

 Method processMapping selects the


Application Configuration
ActionConfig used to process the se-
ModuleConfigImpl contains a collection lection path for this request.
of static configuration information that
describes an application module. For  Method processActionForm retrieves
application initialization, struts-con- the ActionForm associated with a
fig.xml is parsed in order to dispatch mapping or creates and stashes one if
mapping information in instances of Ac- necessary.
tionConfig, ForwardConfig and Form-  Method processPopulate populates the
BeanConfig. properties of the specified ActionForm
from the request parameters included
 ActionConfig contains information on with this request.
how specific events are mapped to
action classes. The mapping is based  Method processValidate calls the vali-
on the path in the request mapping date() method of the specified Action-
Form, and forwards back to the input
 ForwardConfig contains information form if there are any errors.
on where the request will be for-
warded to. Properties name and path  Method processActionPerform asks
correspond to the strut-config.xml the specified Action instance to han-
line : <forward name="next" dle the request, returns an Action-
path="/forwardedPage.jsp" />. Ac- Forward
tionForward extends ForwardConfig
The subclasses of Action are created and
and is not deprecated because of
used by RequestProcessor. It is a wrap-
backward compatibility with version
per around Business logic. To use Ac-
1.02.
tion, subclass it and overwrite the exe-
 FormBeanConfig is a definition of Ac- cute() method.
tironForm beans loaded from struts-
config.xml form-bean  Method execute processes the HTTP
name="userForm" request, and creates the correspond-
type="org.apache.struts.action.Dy- ing HTTP response. Returns an Ac-
naActionForm" /> tionForward instance describing where
and how control should be forwarded.
 FormPropertConfig is a JavaBean rep-
resenting the configuration informa-  Method saveErrors saves the specified
tion of a <form-property> element in error messages keys into the appro-
struts-config.xml : <form-property priate request
name="property1"
type="java.lang.String"/> HTML Form Processing
6400 Shafer Court
 ActionForm represents a general con-
Rosemont, Illinois 60018
Struts Controller cept of data that is set or updated by
847 384 6100 The ActionServlet class is the core of the a HTML Form. Struts will automati-
847 384 0500 fax framework. It is an HTTPServlet which cally set the state of the DynaAction-
receives requests from the browser and Form using the corresponding fields
©2004 Kanbay Incorporated. All forwards it depending on a configuration from the HttpServletRequest.
rights reserved. Kanbay and the
Kanbay logo are trademarks of file : struts-config.xml.
Kanbay Incorporated. Other  DynaActionForm is specialized sub-
trademarks are the property of class of ActionForm that allows the
their respective owners.
creation of form beans with dynamic

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 9: Strut Request Processing

sets of properties, without requiring STRUTS FEATURES


the developer to create a Java class Here are some specific design points
for each type of form bean. which contribute to the frameworks effi-
 DynaActionFormClass is used by Dy- ciency.
naActionForm to manage its internal
state. Struts is not only thread-safe but
thread-dependant. The response to a
request is handled by a light-weight Ac-
User Classes
tion object, rather than an individual
 HelperBean is a “Helper” class; it is
servlet. Struts instantiates each Action
a value object bean which holds the
class once, and allows other requests to
data required by the screens.
be threaded through the original object.
 UserAction is a typical Action, inher-
its the Struts Action class. ActionForm beans minimize subclass
code and shorten subclass hierarchies.
 UserDelegate is based on the Busi-
Another key component in the Struts
ness Delegate Pattern. This is an in-
6400 Shafer Court architecture is automatically populating
Rosemont, Illinois 60018 termediate class which decouples
any ActionForm bean from any request.
business components from the code
Without this component, custom code
847 384 6100 that uses them, encapsulates busi-
may have to be written and instantiated
847 384 0500 fax ness services and access to the
to populate each class of bean.
Model.
©2004 Kanbay Incorporated. All
rights reserved. Kanbay and the The Struts tag libraries provide general-
Kanbay logo are trademarks of Struts Request Processing purpose functionality. Most any JSP tag
Kanbay Incorporated. Other
trademarks are the property of The sequence diagram in Exhibit 9 ex- need can be met by the bean and logic
their respective owners.
plains struts request processing. tags bundled with Struts, and reduce or

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


eliminate the need to write and instanti- call a set of helper classes to access
ate additional tags. needed data. Once retrieved, Struts re-
liance on JavaBeans makes it easy to
Struts components are reusable by the retain value objects and reduce the
application. Utilities bundled with the number of calls to the Integration and
framework have uses throughout most (consequently) Resource layers.
applications. The BeanUtil.populate()
method is a good example. This is used
to populate form beans from a HTTP COMPARING SPRING WITH STRUTS
request, but can also be used to popu- The section aims at evaluating Spring
late any bean from any type of map. with Struts framework. Struts frame-
Reusing components reduces overhead work is the more evolved and widely
and saves resources. accepted framework whereas Spring
represents the most promising new kid
Struts i18n strategies reduce the need on the block.
for redundant JavaServer Pages. By al-
lowing i18n message to be retrieved at Before we make a detailed comparison
runtime, applications that need interna- of Struts with Spring Framework the
tionalization can provide a single page following section lists some of the key
where one page for each language differences in the implementation of the
would otherwise be needed. Meanwhile, two frameworks.
the same messaging system is also used
to handle error messages, providing Struts Framework uses inheritance as
dual use of the same objects. the primary model for using the frame-
work capabilities. Users are typically
Struts is designed with an open archi- required to extend several struts specific
tecture. Struts components are de- bases classes such as ActionForm, Ac-
signed so that they can be subclasses tion etc. The use of concrete inheritance
by an application to provide additional ties the application to the framework
functionality. This allows developers to implementation. The Spring Framework
extend existing classes rather than add on the contrary uses interface based
the overhead of creating and integrating design and IOC to allow user objects to
new classes. Also, Struts exposes its be transparently configured. This makes
internal resources to the application. Spring design more flexible than Struts
This allows developers to leverage ex- design. This however should be weighed
isting components, so they do not have against the fact that Struts introduces
to write and instantiate their own. better discipline in the project imple-
mentation.
Struts is standards compliant. Struts
strict observance to standards leverage Struts uses name mapping approach to
optimizations present in many contain- resolve dependencies of framework
ers. classes to implementation classes. Te
6400 Shafer Court configuration is defined in the struts-
Rosemont, Illinois 60018 Struts is open source and well docu- config.xml and at run time ModuleConfi-
mented. This means developers can gImpl class is instantiated. Spring is
847 384 6100 easily examine the code to identify and based on the Dependency Injection
847 384 0500 fax resolve any potential bottlenecks. Pattern. This allows Spring to be inte-
©2004 Kanbay Incorporated. All grated to middletier without coding.
rights reserved. Kanbay and the
Struts is model neutral. Since Struts
Kanbay logo are trademarks of does not make any assumptions about Struts is primarily intended to be used
Kanbay Incorporated. Other
trademarks are the property of the backend model, an application can in a web application and it is often ar-
their respective owners. implement that portion in the most effi- gued that Action classes which are the
cient way possible. Struts Actions can

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


handoff points to the model are tied to
servlet APIs. Similarly Struts uses tag
libraries which tie it to use of JSPs as
the preferred view technology. Spring on
the other hand uses Application Context
and is view agnostic.

The independence from specific view


technology allow Spring applications to
be tested outside the web container
which is a huge improvement if test
driven development is important to the
request processing cycle.

In what follows we compare Struts


framework with Struts using a series of
criteria.

6400 Shafer Court


Rosemont, Illinois 60018

847 384 6100


847 384 0500 fax

©2004 Kanbay Incorporated. All


rights reserved. Kanbay and the
Kanbay logo are trademarks of
Kanbay Incorporated. Other
trademarks are the property of
their respective owners.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 10: Controller Patterns

Criteria Spring Struts Score

FrontController In- Can have multiple Displatch- Works with single ActionServlet
stances. This acts as
the controller servlet
in MVC
erServlet configured for an ap-
plication. Each servlet will have
its own context information. The
various modules can share a
for an application. The module
concept can be use for logical
separation of modules.

Plugin mechanism to support
common root context. extension without inheritance

Mapping form ac- The mechanism is pluggable. The match is based on url path
tions to handlers The default is BeanNameUrlhan-
dlermapping where the action
specified is the name of the
bean. The other mechanism is
resolution.
No other matching option sup-
ported

the SimpleUrlHandlerMapping,
which has Ant-style pathmatch-
ing capabilities.

Transferring form Uses reflection to populate the The advised way is to create sub-
data to the handlers data to the form controller the
java beans way.
PropertyEditor mechanism al-
class of the ActionForm for every
form. Uses reflection to populate
the Action Form which is re-
stricted to using only strings

lows type conversion

Command Controller In Spring, the controllers come Most controllers have to extend
types, M of MVC in various flavors; one can use
different controllers depending
on the need. For example for a
form submit one can use the
the Action class. Struts1.1 has
DispatcherAction which has the
similar kind of behavior

SimpleFormController, for
grouping multiple requests to
one controller a MultiActionCon-
troller can be used. Wizard-
FormController for wizard-style
manipulation of data objects.

Per Class initializa- Can have one per request, is Once by servlet
tion of Bean, M of
MVC
configurable for single or multi-
ple

Interceptors Can add Handle Interceptors Need to use filters or Extend the
when want specific functionality
to all the request at pre, post
and execute
Action class with changes in exe-
cute method for pre post changes

6400 Shafer Court
Rosemont, Illinois 60018 REQUEST PROCESSING CONFIGURATION
ARCHITECTURE Configuration file has the mapping for all
847 384 6100
Controller the beans. The number of configuration
847 384 0500 fax
files needed, the ability to split the
Front Controller is the choice for both
©2004 Kanbay Incorporated. All information into multiple files repre-
rights reserved. Kanbay and the Spring and Struts framework. This is an
senting one per module etc. This is
Kanbay logo are trademarks of accepted pattern from the Sun J2EE
Kanbay Incorporated. Other shown in Exhibit 11.
trademarks are the property of core patterns. However, the pattern can
their respective owners.
be implemented in different flavors.

FOR INTERNAL USE ONLY © 2004 Kanbay Incorporated


Exhibit 11: Configuration

Criteria Spring Struts Score

Type of configu- Mixed – XML, properties. For rela- XML,use of strut-con-


ration tively small applications, the con-
figuration file can be done away
with and the information included
as Source Metadata.
fig.xml


Multiple con- This is allowed and the various Only with Struts 1.1 is
figuration files
for a single ap-
plication
files can be built into one context
with the parent-child relationship.
multiple configuration
files allowed.

VIEW
This section examines the strategy used for decoupling the actual view resource name
from the controller.

Exhibit 12: View

Spring Struts Score

Name View /URL Path Spring uses a pluggable view Struts use the struts-
mapping strategy viz.., Re-
sourceBundleViewResolver,
UrlBasedViewResolcer, Inter-
nalResourceViewResolver,
config file to identify
the next view through
configuration file

VelocityViewResolver and Ab-
stractCachingViewResolver.

Composite view Can adapt using some exter- Tiles gives this compo-
nal entity as using tiles of
struts
sition


View Technologies Can use any kind of view for Biased towards JSP.
Can use any of the
following as V of MVC
JSP/Tag/JSTL/Page-
e.g. velocity, xslt, and jsp.
Uses view resolvers(above
mentioned) for the same.

flow/xml-xsl/applet

SECURITY MODEL
The security model that each of the framework supports. Does it allow plugging of
some well-known implementations?

Exhibit 13: Security Model

Spring Struts Score

Security includes Acegi is an open source project Struts use the JAAS
Authentication and
Authorization
that is written specifically for
Spring. This security framework is
quite abundant in its features.
specification to sup-
port the security
model.

TRANSACTION
This features looks at any support for declaratively transactions
Exhibit 14: Transaction

Spring Struts Score

Transaction Man- Declarative or pro- Will require programmatic


agement grammatic support for
both local and distrib-
uted transactions
transaction definition through
standard J2EE UserTransaction
interface

VALIDATIONS AND ERROR HANDLING
In this section we examine the validation mechanism and exception response of the
application.

Exhibit 15: Validations & Error Handling

Spring Struts Score

Validation Spring allows validation through Provides a validtor


bean wrapper which are trans-
parent to the developer and ap-
ply to objects in any layer
framework which allow
declarative validations

Error Handling Can define HanlerexceptionRe- Each action can specify
solver to handle unexpected
exception
the error condition for-
ward

PERFORMANCE
Performance criteria of a framework will be vastly different from the performance
characteristics of an application. Some of the characteristics that have been identified
include the no of layers, the heap size, inheritance roadmap etc.
Exhibit 16: Performance

Spring Struts Score

No of data Spring allow bean properties to be set Specific API restric-


translations in
the request
processing cycle
to actual type
Any object can act as a command and
can directly interface with domain layer
tions cause data to
be populated into
multiple objects

Use of the re- The concept of Dependency injection Not much.
flection API. relies heavily on the reflection API.
But with the modern day Java runtime
engines the cost of reflection is not as

it used to be.

Runtime heap Depending on the choice made for a The over-emphasis of


size (no of
classes loaded)
specific layer the no of classes loaded
will vary, but the important fact is that
the framework provides the flexibility
to make the right decisions. The tag
the Tag libraries
makes the view proc-
essing a bit bulky.

libraries for Spring are light-weight

Multithreaded Spring allows objects to be created as Singleton


Command prototype or a singletons


COMMUNITY ACCEPTANCE
The community acceptance criterion looks at the framework from the developer and
the industry community point of view. What features of the framework encourages or
dissuades the community from accepting the framework.

In terms of the community acceptance Struts wins hands down with regard to Spring
framework at the time of writing this document. We will examine some of the issue
that has brought about this viewpoint.
IDE SUPPORT

Exhibit 17: IDE Support

Spring Struts Score

Common Eclipse. The feature list of this plug-in Eclipse, WSAD, JBuilder,
IDE support is quite less. JDeveloper etc. Most of
the well known IDE have
extensive support for the
Struts framework.

Books Professional Java Development with There are plenty of books
the Spring Framework – Wiley publica-
tion.
This book is due out in Dec 2004. This
available in the market
ranging from the begin-
ners guide to the more
advanced ones.

book is written by the authors of the
Spring framework

Online The online documentation on the The online documentation


Documenta-
tion
Springframework site is good for start-
ers, but there is no information for best
Practices or recommendations.
is quite adequate.


Testability of Supports the JUnit testing framework. Struts Test Case—a cus-
application
developed
tom-built test framework
using cactus.

Maintain- About framework, if continues to grow. Very clean, has the logical
ability, in
terms of the
code/
framework
About code very clean, easy to main-
tain once acquired to
separation of classes.
Continuous growing with
the large community
around; Wide availability

maintenance of skills

Compatibil- J2SE 1.3 and J2EE 1.3 (Servlet 2.3, J2EE 1.3 compatible
ity JSP 1.2, JTA 1.0, EJB 2.0), J2SE 1.4 is
required for building the framework.
J2EE 1.2 (Servlet 2.2, JSP 1.1) is good
enough if not using

Spring's web MVC or EJB support. The
framework integrates to 14 other third
party tools / applications.

Skills / From the skill set perspective in addi- Java, JSP, servlets and
learning
curve
tion to Java and J2EE, the developer
needs a good understanding of the
Aspect Oriented Programming. Meta-
data / Annotations concept.
tag libraries. The frame-
work is not difficult to
understand. Easy as most
developers already using

for long time now

CONCLUSIONS
The above discussion along with earlier discussions about the direction of the J2EE
specification seem to indicate that Spring will have a significant impact on the way
applications are built and since Spring MVC is based on the same set of principals it
should form part of the consideration set for any MVC implementation
Considering that Spring scores over Struts on most technical parameters and is rapidly
catching up on the community acceptance is a strong reason to further investigate
Spring in the context of a specific project particularly in case of Greenfield develop-
ment

Struts however offer a strong accepted solution and there seems to be no compelling
reason for porting an application currently in Struts to a Spring MVC framework

Adoption of Spring may also be viewed in the context of technology usage on other
tiers

Finally the question of standards conformance should be carefully considered and is a


very important consideration while making any choices.

REFERENCES
 Spring: http://www.springframework.org
 Sun J2EE Core Patterns:
http://java.sun.com/blueprints/corej2eepatterns/index.html
 Struts: http://struts.apache.org
 Java BluePrints: http://java.sun.com/blueprints/patterns/MVC-detailed.html
 Appendix A: http://java-source.net/open-source/web-frameworks
 Appendix B: http://www.softwarereality.com/programming/ejb/conceptual.jsp

ABOUT THE AUTHORS


Kanbay’s Shared Architecture Services team includes the company’s leading
distributed systems architects and designers. The group advises and implements
architectural solutions for Kanbay clients.

The SAS team is led by Chetan Juneja, Kanbay’s Chief Architect. Chetan holds a
Master’s degree in Computer Science and has over 10 years of experience building,
designing and architecting distributed systems.
APPENDIX A: LIST OF OPEN-SOURCE MVC FRAMEWORKS

Struts
The core of the Struts framework is a flexible control layer based on standard tech-
nologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various
Jakarta Commons packages. Struts encourages application architectures based on the
Model 2 approach, a variation of the classic Model-View-Controller (MVC) design para-
digm.

Category Web Frameworks

License Apache Software License

HomePage http://jakarta.apache.org/struts/

WebWork
WebWork is a web application framework for J2EE. It is based on a concept called "Pull
HMVC" (Pull Hierarchical Model View Controller).

Category Web Frameworks

License Apache Software License

HomePage http://www.opensymphony.com/webwork/

Spring
Spring is a layered Java/J2EE application framework, based on code published in Ex-
pert One-on-One J2EE Design and Development. Its flexible MVC web application
framework, built on core Spring functionality. This framework is highly configurable via
strategy interfaces, and accommodates multiple view technologies like JSP, Velocity,
Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web
tier based on any other web MVC framework, like Struts, WebWork.

Category Web Frameworks

License Apache Software License

HomePage http://www.springframework.org/

Maverick
Maverick is a Model-View-Controller (aka "Model 2") framework for web publishing
using Java and J2EE. It is a minimalist framework which focuses solely on MVC logic,
allowing you to generate presentation using a variety of templating and transformation
technologies.

Category Web Frameworks

License Apache Software License

HomePage http://mav.sourceforge.net/

SOFIA
Conceptually, SOFIA is similar to other J2EE MVC open source frameworks, like Apache
Struts. But SOFIA sets a new standard for Java development by delivering so much
more in a framework matching best-of-breed tools integration with robust JSP class
and tag libraries. SOFIA shortens application development time on the strength of its
visual development capabilities and pre-built Java components that dramatically sim-
plify coding.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://www.nextapp.com/products/echo/

Jucas
Jucas is a web-framework which brings together the pull MVC concept with component
orientated design GUI programming.

Category Web Frameworks

License Apache Software License

HomePage http://jucas.sourceforge.net/

WebOnSwing
WebOnSwing is a revolutionary multiple environment application framework that al-
lows you to create web applications in the same way you develope a desktop one. You
dont need to use JSP files, special tags, XML files, requests, posts, etc. Everything is
Java and pure HTML files that comes directly from the graphic designer. This frame-
work constructs and handles html pages with Swing components, allowing to use MVC
architecture and all the facilities provided by Swing in the web.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://webonswing.sourceforge.net/

Chrysalis
Chrysalis is a Java web development framework. It has a different focus from most
Model-View-Controller (MVC) web frameworks. Chrysalis controllers resemble normal
Java classes with multiple methods. Client request URLs are mapped to each controller
method.

Category Web Frameworks

License GNU Library or Lesser General Public License (LGPL)

HomePage http://chrysalis.sourceforge.net/

VRaptor
VRaptor is a MVC web framework. It is highly based on the Inversion of Control princi-
ples, using constructor injection to decouple your components from your business logic
classes.

Category Web Frameworks

License Apache Software License

HomePage http://www.vraptor.org/
APPENDIX B: SOME ISSUES WITH EJB SPECIFICATION

Exhibit 18: Issues with EJB Specification


Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

1 EJB represents a radical departure from the Beans model. Beans was based on the
(proven) component model also used in Delphi. This means that for projects that are
migrating to EJBs, much of their code base is no longer valid.
Very little effort was made getting EJB to naturally extend the Beans specification
(remember JavaBeans are not just about GUI widgets).For example, there is no men-
tion of Events in the EJB model. Enterprise Beans don't have property change events
or vetoable events, or indexed properties. The specifications focus almost entirely on
the server side specification and hypothetical roles.

2 A rigorous set of examples and design goals for application programmers has been
missing from the start. Instead the focus has been on remote objects and pessimistic
locking, rather than the high performance and soft locking required by most Internet
applications today.

3 EJB is based on an Object Pooling optimisation. Optimisations should not be incorpo-


rated into the design, but left for vendors to decide and compete on. The logic of
basing a system on saving a resource as cheap as memory seems absurd.

4 Sun's recommendation to "Use Container-Managed Persistence When You Can" is


contrary to our experience. I am sure we're not alone in that CMP seems to be useless
for complicated applications.

5 The EJB specification makes no reference to other well known distributed system de-
sign references—for example the ISO Basic Reference Model of Open Distributed
Processing 1992. Most seminal communication specifications make reference to the
ISO Open Communication Models. Either there is a lack of theoretical grounding, or
perhaps the designers didn't think it was worth mentioning.
The above-mentioned ISO ODP reference model has several goals for a distributed
system. Many of the important goals have not been met—in particular (points 6-9 as
follows):

6 The EJB spec doesn't address access transparency. Local and remote object definitions
are not transparent, as you inherit from a different interface and have to cast using
the narrow convention.

7 The EJB spec doesn't address performance transparency. The performance solutions
for EJB involve radical redesign of your code, such as session-based methods, value
objects, entity bean serialization or client side caching.

8 The EJB spec doesn't address migration transparency. If any object moves, the client
must throw away the remote or local interface and get a new one.

9 The EJB spec doesn't address Concurrency transparency. There are no clear sets of
locking strategies to suit different application programming tasks. The application and
EJB programmer is left to handcraft locking strategies.

10 The only justification for EJB is on large projects, yet EJB makes those large projects
larger still, and yet more unwieldy. You need to scale to get EJB to perform.

11 Role based class/method security is rarely useful. Data security is far more important.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

12 EJB Query Language is another language to learn. This is reminiscent of the situation
with WML, where an attempt to write a simpler language than HTML failed because
they didn't just simplify HTML. Instead they started from the ground up, having de-
cided erroneously that they could do a better job themselves.
EJB Query language doesn't support many SQL operators, (e.g. subqueries, IN, ALL,
ANY, String comparison, ORDER BY, GROUP BY).
There is a good critique of EJB-QL here.

13 The specification does not provide for proper handling of views or read only tables.
Back in the real world, read only tables and views are very important.

14 EJB only handles first class objects (i.e. beans that have primary keys). It would be
nice if it also handled second class objects (do not have primary keys), where they
have a one-one relationship with a first class object.
For example, a Cash object might contain a currency and an amount. Using CMP En-
tity Beans you would be forced to have a Cash table. A better design would be to
automatically map the Cash.currency and Cash.amount into the parent table's col-
umns.

15 No proper handling of validation (e.g. String lengths). For a specification whose main
purpose is reading and writing to a database, this is a surprising omission.

16 No proper handling of Enumerated Types. Enumerated Types represent fixed sets of


data, such as Sex, Industrial Classification, or Marital Status. It should be possible to
use them as properties on Beans.
It has been argued that this is more of a Java issue, i.e. a deficiency in the Java lan-
guage rather than EJBs per se. This is not necessarily the case though. For example,
our JBeans spec includes Enumerated Types defined via a standard interface and an
EnumeratedType abstract class.
Adding Enumerated Types to the Java language would be better; but the EJB spec
would definitely benefit from a similar addition.

17 EJB doesn't make a clear separation between the components and the machinery that
is supposed to persist it. For example a bean can remove itself, which assumes a bean
is always persisted and it must always be tied to a persistence mechanism.

18 Entity Beans bind the business logic with the persistence mechanism. Hence the need
for Data Access Objects. If the persistence was orthogonal to the beans this function-
ality would have been accommodated more naturally.

19 Optimistic locking is not accounted for. The EJB spec assumes either pessimistic lock-
ing or not locking, or roll your own. There could have been a locking interface; or a
way to specify a logical concurrency mechanism like isolation levels.

20 Most 'fast' EJB patterns seem to involve using sessions that go straight to the metal.
Half the time is spent navigating, so half of the system ends up being rewritten.
Entity beans only appear to be useful in single entity transactions, but not where the
entity bean needs to know about its dependent beans. When you save a bean, the
graph of dependent beans should also be saved—but it doesn't work like that.
For EJB you can specify cascading deletes, but not combinations of creates, updates
and deletes. To save a graph of beans you must create your own client side User
Transaction and call each create on the home, set on the bean and remove on the
bean. The beans should understand what has been changed in the graph and update
the database accordingly.
If we were "putting the boot" into EJB, we would suggest that this means EJB is only
half complete.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

21 There is no meta-data for business, i.e. no meta level to describe your business. Just
code.

22 EJB tries to address both the client side interfaces and the service provider interfaces.
Really as a client we should only care about the client side interfaces. This would
make EJB open to different implementations.

23 No standards for writing Session beans as Beans. Yet this approach is one of the most
talked about on the web.

24 There is no concept of dependency, so that a bean is stored, removed or updated at


the same time.

25 There is no concept of whether the primary key is generated externally by the appli-
cation, internally by the container, or automatically by the database.

26 EJB is designed to handle high-transaction units of work in a distributed environment.


A very small percentage of applications need this. When we define high-transaction
usage we mean thousands, not hundreds. Most users need only tens a second. The
EJB spec also neglects applications that need to return static data, or real-time data.
There are not designs in place to return these objects.

27 No standardised integration with content management tools (other than "roll your
own" solutions via JSP, for example). For large web sites, it isn't clear how these
would integrate.
This is more of an issue with J2EE as a whole than EJB by itself.

28 To attach enterprise development without going to a higher level, without approaching


it with a blueprint, is like trying to dig a tunnel through a mountain with ever so
slightly sharper spoons. They shouldn't be working on this level.

29 Sun doesn't have a joined up strategy for persistence, i.e. JDO, JDBC, Java Blend,
serialisation, XML, EJB without any common interfaces. This is similar to the case with
GUIs, i.e. Swing, AWT, MIDP, and web front-ends which they are trying to address
with the mysterious JavaFaces. This gives the impression that the various design
groups at Sun are out of control.

30 ACID is not always wanted. For example, a search engine wants high performance,
availability, in exchange for accuracy.
As with many of the issues raised in this article, the obvious answer appears to be:
"So don't use EJB for this type of work." Unfortunately, we believe that this blinkered
approach seriously limits EJB's usefulness. Why should it be limited to such a narrow
field of use, simply because of some erroneous assumptions made early on regarding
the sort of features that all enterprise applications would surely want?

31 Most web apps are not very transactional. EJB comes from a TP/MTS type background.
Perhaps it should have been called TJB, Transactional Java Beans, so that people knew
where it belonged. As it is, EJB co-opts areas that simply don't belong to it. It's a
baroque framework for transactional Java beans, which tries to wear the clothes of the
enterprise emperor.
EJB is very transactional—it sucks when it comes to high performance queries, read-
only work.

32 EJB hasn't really addressed the issue of efficient access to remote objects. Effectively
you have hand code. It would have been better to have client side beans where ven-
dors could have generated different options. At the risk of plugging our own product,
JGenerator allows you to do this.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

33 There is no clear design for returning Relationships between beans. Should you return
a primary key (and look it up on the client)? Or return a handle, which does the look
up but needs Bean managed code, or return the related beans remote interface which
in turn means referencing the remote bean from the server?
Container managed relationships can only exist between beans whose homes are on
the same server. This makes it impossible to deploy an enterprise system where one
bean references a bean in another database automatically. For example, several
product databases may reference a central customer database. There is no way to
automatically generate a getCustomer() method on a product. Not very Enterprise.

34 It's difficult for a bean to tell the server when it is dirty, or read-only. This is supported
in some servers, not in others. This should become part of the specification.

35 Use of CMP beans locks you very much into the vendors' proprietary mapping tech-
nology. Beware of the apparent ease of use that CMP tries to offer.

36 The EJB Spec imagines the role of a container builder and a server builder. This as-
sumption that there would be separate container products that would run in the appli-
cation server is incorrect. Hence the service puts unnecessarily tight constraints on
state control. This should have been left up to the vendors.

37 Development is very slow. For example, the development cycle is tens of minutes,
rather than seconds, simply to change a small value in a JSP. This is a huge project
killer. Increased development time hardly helps with 'Internet time' projects.

38 There is no concept of a design time state, like in the Beans model that allows for a
quick development cycle.

39 EJB represents a huge learning curve. The EJB spec is supposed to help, but seems to
hinder. It's very complex. Even for the most experienced engineers and architects,
getting all the niggling details correct makes development painfully slow.

40 Many sites do not need EJB complexity, yet people use EJB for the sake of fashion, or
getting skills on their CV. Too many people are happy to sacrifice the future of their
company/project, in order to get 'sexy' skills.

41 There is no way of knowing when set property values are done. Explicit transaction
demarcation is done at the property level, not at the Bean level. If there was a store
method on a home/session this would do this.

42 There are no standards for optimising Entity Beans, serializing the whole bean or
sending property sets.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

43 One way to fix the previous two problems would be to introduce "smart stubs" *. In-
stead however, the programmer is expected to write straight to the wire for every
property get or set, or to use facades, dependent objects etc. That's an awful lot of
extra code, especially when it conceivably affects every single entity bean in your
application.
* Smart stubs are a concept that CORBA came up with. A client side CORBA stub
would have another stub subclassed (and could be delegated from). So the client side
programmer thought they were going straight to the remote stub, but the application
programmer had the opportunity to 'fiddle' with the call before it went.
Subclassing meant you could only do a little bit of fiddling, but delegation allows you
to completely alter the RMI method call, so that you might write to the client a se-
quence of "set" method calls, and all the time it would be storing the set values in a
property list, instead of shoving them over the wire every time.
Then, when you call the commit transaction method, all the sets that you have done
on all the objects in that transaction are bundled up and sent in one message. Con-
versely all the properties can be pulled over when you call the first get, so you're not
getting every tiny property every time you call a get method.
At Javelinsoft, we do this in our CJBs (Client Java Beans) by serializing the Entity
Bean from the EJB server when we make the first get call, and filling it up and squirt-
ing it back when we say save on the Home.

44 Stateless session beans are supposed to be the most scalable, yet they are not much
more than RMI. However we still need to jump through all the hoops to get them
working.

45 It isn't easy to put EJB in Applets. There is no concept of a lightweight interface.

46 EJB does not have count methods optionally automatically generated. This feature is
used in many applications I have worked on to save loading objects into memory.

47 Non web app client access to EJB is vague, and inconsistently supported. Sometimes
an application server will supply you with a jar to include in your application to get
access to the EJBs; sometimes you just have to figure it out yourself and end up in-
cluding several megabytes of jars.

48 The spec for EJB cross beans mapping is constantly under change, and inconsistent
across servers. It's also not flexible. The result is that you cannot easily port from one
application server to another.

49 We need to use value objects to get any real performance, else each get/set makes an
RMI call. Why was this concept of local stubs or property sets not put into EJB?
Performance should not be an irrelevance.

50. EJB wizards are often shaky and dangerous. They end up creating code that simply
won't work. So you waste time thinking it must be your own problem somewhere. For
example, the RI (Reference Implementation) 1.3 container entity bean wizard misses
out "throws CreateException" on ejbCreate.

51 The RI seems to have had 0 to little Q.A. For example, 1.3 RI code generation tools
simply produce wrong code. Their entity bean managed findByPrimary would never
work. This is of no help to anyone learning EJB.
As the RI is the "Reference Implementation" this is very bad. No one expects the RI to
be fast, but we do expect it to be a model of compliance and correctness.

52 The WAR/JAR/EAR model is horrible for development and deployment. The deploy-
ment spec is opaque, using the Russian Doll metaphor.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

53 EJB deployment is incredibly fragile. Miss setting a property and the container won't
use a sensible default. Of course this depends on the container, but mostly they sim-
ply throw a vague error message and refuse to continue. This is just plain unhelpful
—"jobsworth", even.
The servlet world has it easy in comparison—e.g. the "invoker" servlet executes
anonymous servlet classes that have not been defined in a web.xml file (usually maps
to /servlet/*).
In other words, servlet engine writers go to special efforts to make deployment easy.
Easiness is what it's all about. EJB containers don't have the equivalent of a default
web.xml file that they can inherit default properties from.

54 There is no standard way to deploy an EJB application. The details change with each
server, and (worse still) with each revision of each server.

55 EJB needs to be more IDE-friendly, particularly when it comes to deploy-


ment.Deployment is not always opened up to tools, e.g. RI 1.2.2/1.3 uses batch files
which call Java. Its deploy/package code is not meant to be called by tools. The RI
uses the broken concept of current directory, i.e. must be called from a DOS window,
not from an IDE VM.

56 The EJB spec has too many fictitious roles. In reality there are container/server pro-
viders, and application providers who develop, assemble, deploy, and administer the
EJB server. The EJB spec should reflect this reality.

57 There is no such thing as cross platform EJB. Each platform has its own horrible bugs.
Escape one system to fall prey to another.

58 Developers have to repeat the same meta-data in the code as SQL, as client proper-
ties as server properties, as XML attributes.

59 Container managed EJB often requires you to specify a lot of what would be in your
code, for example the SQL.

60 Administration is different with every server. There is no standard for administering


the deployed EJBs.

61 XML is all about interpretation. Different vendors interpret the XML differently. For
example (on the servlet/JSP side), web.xml's <welcome-file-list>. Some see this as
'look for these files in this order', others as 'these files should be here'.
Of course this sort of misunderstanding just can't be helped sometimes, but is in-
cluded here as something to be wary of—it's an example of how ambiguity can creep
into a seemingly bullet-proof spec and cause standards to fragment.

62 The specifications are continually changing. That's ok, but when new versions cannot
run old applications without major changes, then we have a problem.

63 The server vendors have graced us with some remarkably vague and misleading de-
ployment tools, e.g verifiers that spout unhelpful error messages, or pass classes that
then fail on deployment.

64 Loose coupling between the bean and interface. The XML is not strongly typed, i.e. too
much room for error. Very little use of reflection to work out class relationships.

65 Deployment of code, in order to test it, is a horribly complex, click-laden process. As


well as involving many stages, there seems to be no proper way to automate it, espe-
cially if you are attempting to target many different EJB servers.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

66 The basic ejb.xml, web.xml and application.xml descriptors are not sufficient to de-
ploy. The result is that further descriptor information must be written using app-server
specific XML. This means that every ear must be changed to be deployed. It would
have been better to have defaults set up so that a minimally defined EJB would deploy
and run without modification.

67 The XML descriptors use ambiguous names—for example, displayName isn't just the
display name, it's used as the reference name.

68 An EJB ear should be able to be deployed on ANY compliant EJB server, with no
changes to the ear.It should expose and advertise the environmental items that can
be changed (like war mount point), and those that MUST be changed (like database
connections).
However, there should be no requirement on the ear developer to produce X different
versions, for all the servers out there. This seems to be the current state, which is
madness.

69 The Validator passes descriptors which later fail on deploy. For example (using Cata-
lina/Tomcat in RI 1.3), try creating a war file with multiple entries with the same
name. The war is passed on verify, but of course fails to deploy.
A connected problem is that once deployed, there is no way to automatically test that
your beans have actually deployed.
These might not be such terrible issues, but they merely add time and frustration to
an already slow process.

70 The real bottleneck is data access and transactions, of which the average database
can only handle about 50-100 a second. EJB needs to take on board replication server
duties in order to really speed things up.

71 There is very little scope for run-time optimisation. The EJB specification contains no
standard flags or extensions for improving performance. For example, WebLogic has
used a 'dirty' flag to help determine if the object should be written down to the data-
base. Despite being a well-known extension with well-understood semantics, this did-
n't make it into the latest specification.

72 EJB performance is very slow, and uses lots of resources. It's costly to scale. The
"fetch my primary key" query model suggests that the designers did not understand
how relational databases work: The EJB queries return a list of primary keys. Each of
these primary keys are then used to perform another query to the database. This
operates in a way contrary to the way relational databases are optimised, i.e. on sets
of rows. The whole philosophy behind EJB object pools is to re-use objects, and not
cache them. This relates to Damnation #3—that EJB is designed to preserve memory,
when memory is not a scarce resource—in fact it's a dime-a-bucket at the moment.

73 EJB cannot scale. Because your entity beans need to be synchronised across all the
servers that they are deployed on, the amount of network traffic multiplies.

74 Black box. When your deployed system goes slow you can't work out why unless you
have the container source.

75 An EJB server is harder to build than a servlet engine. Hence they tend to be far more
fragile and mad, which is hardly a good base for an enterprise application.

76 Sun said that to be 2.0 compliant an EJB app-server would also have to support 1.2
compliant EJBs. But their own reference implementation does not support 1.2 compli-
ant beans, because the Sun specific 2.0 XML interpretation throws errors with 1.2
compliant XML.
Exhibit 18: Issues with EJB Specification
Source: http://www.softwarereality.com/programming/ejb/conceptual.jsp

77 Sun's J2EE compliance tests seem to let some pretty obvious omissions through. For
example HP-AS doesn't handle nested archives (i.e. referencing one jar from another
through a declaration in the Manifest file), which is part of the J2EE spec. A server can
be officially branded J2EE, even if half its J2EE features are broken. The promise that
they'll be made to work in the next service release doesn't quite cut it, and often ends
up not happening.

78 Where is the large-scale EJB usage? The thousands of downloads of J2EE, WebLogic,
HP-AS, JBoss etc don't quite tally with the number of real-life EJB systems in use.

79 Where is the large-scale usage of EJBs? How many companies are really using EJB for
massively scalable back-end systems?

80 Where is the thriving EJB component marketplace 3 years from inception? The situa-
tion seems similar to what was said of C++. VB/Delphi/Java had and has loads of
components, as it is so easy to write them.

81 The EJB specification was not focused on any applications. There should have been
two or three big, complex, real world apps that needed to be expressed in EJB as a
testbed.
It took Sun about 2 years to come up with Pet Cemetery, and even then, it proves
nothing except that they don't have a clue. This same criticism is just like that of
Swing—it took years to come up with proper test apps, e.g. Forte!

82 Sun's main revenue stream is from hardware, not Java. Their profit driver is to sell
hardware. This explains why EJB has not been reigned in and rationalised.

83 There is no real synergy between EJB and the rest of J2EE.

84 Most, if not all, EJB articles on the web seem to be about hacks, bugs, workarounds,
optimizations, as opposed to glowing success stories. Where are they?

85 The creators of the EJB spec are in a privileged position. It's very easy to define huge,
complex specifications and expect the industry to forever be trying doggedly to catch
up with actual implementations of their mad schemes and "visions".
It's not so much an OO Utopia as a "Complexia". It would be much harder for them to
try and implement their own specs (as they discovered with the RI mess).
The server vendors don't get a chance to make their servers useable or robust, as
they're forever trying to catch up with Sun's latest promised feature-list made on their
behalf. Then there's the even bigger problem of supporting legacy versions (for those
vendors that can be bothered with such "trivial" notions).

86 Brave New World—this isn't just a comment on EJB, but on the state of enterprise
computing:
Everyone expected the OO dream to materialise with interconnected, co-operating
objects whizzing around global networks—instead we have gronky EJBs and labour-
intensive EAI systems (e.g. BizTalk), much too complex for their own good.

87 The basic idea behind EJBs, and Sun's approach to APIs, is good. The principle of de-
fining standard specifications for the industry to follow is a noble one. But something,
somewhere, has gone terribly wrong.

S-ar putea să vă placă și