In-Depth
Servlets and EJBs: Friends or foes?
- By Max Dolgicer, Gerhard Bayer, Michael Bardash
- July 1, 2002
Our return to the columns of ADT after a two-year absence comes after a
period of intense change -- the demise of the dot.com phenomenon (which almost
overnight became the dot.bomb experience), the introduction of too many
buzzwords and standards, a plethora of new products that implement -- or just
claim to implement -- the latest buzzwords and standards, and much, much more.
As always in this business, vendor marketing dollars moved quickly from
yesterday's ''du jour'' technologies a couple of years ago and are now promoting
J2EE, .NET and, of course, Web services.
However, though the ever-increasing number of buzzwords does create a degree
of confusion, one can oftentimes easily follow the common thread and common
sense of what we call ''the buzzword evolution.''
A couple of years ago one of our engineers jokingly declared: ''after the
invention of the state machine everything in computing is a hack.'' While this
is far from reality, many industry veterans would concur that while the
buzzwords and standards do change all the time, the basic principles of
distributed computing and middleware remain the same. Just follow the trail of
''buzzword evolution'' in the common vocabulary of magazines. IDL (Interface
Definition Language) ''got replaced'' by WSDL (Web Services Definition
Language); SII (Static Invocation Interface), DII (Dynamic Invocation Interface)
and RMI (Remote Method Invocation) ''were taken over'' by SOAP (Simple Object
Access Protocol); and finally, Service Oriented Architecture replaced ''Whatever
Oriented Architecture'' was in vogue.
Yes, there are more standards now than ever before (skeptics are referred to
the list of XML standards governed by the World Wide Web Consortium, or W3C).
But at the end of the day, only a few standards matter to developers.
The ''buzzwords and standards'' evolution begs the question of whether
middleware choices are more confusing for IT executives and development managers
now than they were two years ago. As a consulting company always trying to stay
at the front of the middleware revolution (and evolution), taking advantage of
many opportunities to implement important projects using a multitude of
middleware technologies, we can report that unfortunately, the answer to the
question is not a binary yes or no. The good news is that there are some
middleware choices that are becoming close to binary. And at least when it comes
to the development of brand-new component-based e-business applications there
are really only two middleware platforms to choose from -- J2EE and .NET.
However, the reality is that most companies have long focused less on
developing new applications than on integrating existing applications. That
reality is even more true today as IT budgets undergo more scrutiny than ever
before. According to recent monthly CIO surveys conducted by investment firm
Morgan Stanley, application integration was cited consistently as a top priority
for 2002 and beyond. The bad news is that no single middleware solution has
emerged from the pack to become an obvious choice for projects that are focused
on application integration. So the technologies and products that enterprises
can evaluate today remain very complex and are even more confusing than they
were in earlier years. Today, viable integration technologies include Message
Oriented Middleware (MOM), Message Brokers, CORBA, J2EE-based application
servers and Microsoft's .NET.
As middleware consultants, important questions we hear regularly include: Are
the J2EE-based application servers ready to undertake complex EAI projects? And
what are the long-term risks associated with the use of proprietary Message
Brokers?
In this and future articles we'll try to answer some of the most asked
technical questions, including: What are the differences and similarities
between J2EE and .NET frameworks? Are J2EE-based application servers ready to
become the technology of choice for EAI projects? And what are the key
challenges in the development and deployment of J2EE applications?
In this article we tackle a question that we have been asked repeatedly
during the past few years. As J2EE-based application servers like BEA's WebLogic
Server and IBM's WebSphere gain more widespread acceptance, should Java servlets
or Enterprise JavaBeans (EJBs) be used as a foundation for e-business
applications? Most of the early Web-based J2EE applications have been developed
using servlets as a base for two main reasons. First, the servlet model offers
more simplicity than EJBs and is easier for IT developers and managers to
comprehend as they get started with the technology. And second, the majority of
the early projects are focused on the so-called ''low-hanging fruit,'' or new
e-business applications that focus on presentation-centric applications and do
not have high developer demands in terms of complexity, scalability,
availability, reliability and extensibility.
Meanwhile, the vendors state that the purpose of J2EE application servers is
to support high-end enterprise applications and to serve as the new, strategic
middleware platform for all application development and deployment. It is
therefore important to understand the difference in capabilities of servlets vs.
EJBs so that the suitability of one approach over the other can be determined
given the requirements of a particular project, the readiness of IT personnel,
budgets and realistic time-to-market.
Popular technologies
Both Java servlets and Enterprise
JavaBeans are popular technologies, and both can play a prominent role in
enterprise architectures. Frequently, suppliers and users view these
technologies as competitive, especially for Web-centric applications. Indeed, on
the surface, servlets and EJBs can both be used to allow thin clients, such as
browsers, PDAs and the like, to access enterprise data. Two variations on a
classical architecture -- a thin client (such as a browser) accessing a servlet
that is in turn connected to a back-end system or database; and a second
variation that shows a client accessing an EJB through a presentation gateway,
such as an HTML servlet -- illustrate this contention.
Indeed, from the browser client perspective, there is not much difference
between the two technologies -- both bridge between presentation and back-end
functionality. And, in many cases, servlets are considered to be a better choice
because their coding and deployment requires simpler skills and shorter times
than those required for using EJBs, which deal with a whole spectrum of complex
issues, including many additional APIs and rules. Of course, when an
enterprise-strength architecture is in question, neither the browser client
perspective nor the simplification of the development process is a good enough
justification for the choice of technology.
The fundamental difference between servlets and EJBs becomes apparent when
such essential design objectives as architectural robustness and business
agility are brought into focus. Then, issues like scalability, state management,
flexibility of entity relationships and richness of the cooperation metaphor
start to play a prominent role in the technology selection process. We intend to
show why EJB-based architectures can handle such concerns better than
servlets-based technologies, and why a clear understanding and recognition of
this conclusion is required when new, complex applications are being developed.
We may be giving readers the impression that we are biased toward EJBs as the
preferred vehicle for enterprise architectures. However, our view is that EJBs
and servlets are orthogonal technologies that, rather than competing directly,
are mostly complementary. To compare EJBs and servlets is not like comparing
apples to apples. It is not even like comparing apples to oranges -- it is more
like comparing apples and oranges to the crates and barrels that are used to
store and transport them. This becomes obvious when the essential differences in
intent, focus and, if you like, domain philosophy of the two standards are
investigated.
Servlets cater primarily to the delivery of dynamic content to browser-based
clients. They are narrowly focused on facilitating presentation, such as
programmatic translation and preparation of HTML, and on relief from handling
lower-level details of HTTP. This is the extent of the role servlets play in the
framework of the J2EE standard.
On the other hand, the EJB standard was devised with the vision of a common
pattern for component architectures in mind. It deals principally with enabling
the development and deployment of a business application as a collection of
components into a framework of powerful and comprehensive infrastructure
services (which can include Java Database Connectivity (JDBC), Java
Transactional Service (JTS)/ Java Transaction API (JTA), Java Messaging Service
(JMS) and the like). Rather than prescribing any specific role (such as HTML
rendering or HTTP encapsulation), the Enterprise JavaBean component model is a
mold for generic business components whose exact specialization is left to the
application designer to establish. In other words, the servlets specification is
a somewhat narrow standard specialized on the presentation layer of
applications, while the EJB standard is a broad enabling technology.
This distinction becomes more apparent when directly comparing the
characteristics of EJBs and servlets to evaluate their respective applicability
to enterprise architectures.
* A servlet is a faceless Java object. Beyond some features
mandated by its base class, it is amorphous and can have arbitrary internal
composition. On the other hand, by contract, an EJB is obliged to implement
specific interfaces (such as the home interface, activation and deactivation
interfaces) and mandatory properties (such as primary key, for example) that
promptly tie it into the cooperation environment (the container).
* A servlet has to implement a rigid set of methods with predefined
signatures just as Enterprise JavaBeans need to implement a set of methods
imposed by the EJB specification to fulfill the contract with the container.
However, the EJB can also define arbitrary methods that best suit its business
semantics.
* Servlets have very thin support from the environment they are deployed
into, which is mostly limited to HTTP-related matters; EJBs enjoy a wide range
of powerful and comprehensive infrastructure services that are provided by the
container. Examples include the generation and handling of remote interfaces,
component factory services, component instance identification, distributed
transactions, automatic persistence for Entity Beans and declarative security.
* Basically, servlets are focused on one task: reacting to HTTP requests with
HTML responses in a stateless manner (in fact, state may be maintained via an
HttpSession object, but it is not comprehensive and requires explicit client
cooperation via session cookies). EJB behavior is defined at a higher level of
abstraction: EJB method invocation does not stipulate any syntax or semantics to
the invocation arguments or to the maintained state.
* By design, the aim of EJB is to segregate business functionality from
infrastructure services (such as life cycle management, transaction and security
contexts and persistence). Because servlets are not integrated with the J2EE
infrastructure services, they encourage application developers to deal with
lower-level J2EE APIs directly, and entangle business functionality with logic
related to infrastructure services.
* The servlets specification does not address enterprise concerns such as
load balancing and failover. On the contrary, inherent scalability and high
availability of services is a declared responsibility of the EJB container. (It
should be noted that some servlet engines do support clustering and load
balancing. Curiously enough, these are the engines that are embedded into EJB
application servers such as WebSphere and WebLogic).
In other words, servlets do one thing and do it well -- they provide a shell
for the presentation layer of a Web-based application; EJB is a complex
framework for implementing widely dissimilar business functionality in a
coherent and comprehensive fashion.
Servlets expose; EJBs encapsulate
The other point of
distinction between servlets and EJBs is that, in our experience, in the
majority of cases, servlets are used to expose business data, whereas
EJBs are used to encapsulate business functionality.
A classic use of a servlet would be to parse an HTTP request, access a
database for inquiry or update, and to compose an outgoing HTML reply. (A less
common use of a servlet would involve passing a serialized Java object between
itself and a browser-side applet. This scenario will be discussed later.) For
example, a browser may submit a request for an airline schedule, and the servlet
will fetch the data from the database and format the reply as an HTML table.
Also, the browser may submit a filled form whose elements will be stored by the
servlet in a database table. In either case, it is the data, not the behavior,
the client is interested in.
Arguably, HTML data-level cooperation achieves a great level of independence
between the presentation at a client (in this case the browser) and the
processing at the server (the servlet). The interface between the client and the
server is primarily concerned with passing data; there is no API specific to any
particular business function. The browser client displays HTML returns
unconditionally (subject to its validity, of course). Thus, if the servlet
implementation is changed to render richer replies (such as embedding sound
clips, for example), the client will benefit from this extended business
functionality automatically and transparently. However, if the servlet is
changed to display, for example, the latest cricket results instead of stock
quotes, all the same data will be unconditionally rendered by the client, much
to the user's dismay.
In other words, the client's horizon extends all the way to the data and the
servlet acts merely as a rendering agent that enables the client to access the
database.
Separating the presentation by the browser client and the processing in
servlets achieves a higher degree of independence compared to an EJB-based
architecture because it does not rely on the strong coupling that the interface
of an EJB with rigid business semantics imposes. However, this comes at the cost
of compromising business process integrity. This might not be a cause for
concern for simple Web browsing interactions, but from an enterprise-strength
B2B/B2C perspective, cohesiveness of the end-to-end business process flow must
be protected. This objective is best achieved by encapsulating business behavior
in services, and service granulation and exposition is precisely the domain of
the EJB.
With a typical EJB implementation, a client gains access to business
functionality through a presentation gateway, whereby the latter provides a
rendering agent for business functionality as opposed to data. Thus, a typical
use of an EJB would be for the client to remotely invoke the server-side
service, which may or may not result in any data being returned to the client,
but which would definitely result in some meaningful processing having taken
place at the server side.
Two-tier vs. three-plus tier
Another way to contrast
servlets and EJBs is to assert that servlets by intent serve to accommodate a
classical two-tier application (where the presentation and data access/business
logic tiers are commingled within the servlet and the data store). On the other
hand, EJBs tend to three-tier or multitier complex cooperative environments.
Apparently, the flexibility of interpretation built into the servlets
standard permits us to break this data-only paradigm easily. Nothing prevents a
servlet from being engineered in such a way that it encapsulates a business
service. Practically, this can be achieved in a number of ways. For example,
instead of only accessing a database, a servlet implementation may invoke
back-end functionality that has been written in Java via an RMI call, or a
servlet may exchange serialized Java objects with a browser-resident applet.
These and other design patterns that turn servlets into business logic capsules
are well known and quite popular.
In practice, it has become a common architecture approach to allow servlets
to benefit from their amorphous ''anything goes'' internal structure -- or,
better yet, their lack of any internal structure. Nothing prevents servlet
implementations from internally integrating with a variety of technologies like
RMI/CORBA, JNDI, JMS, JTS/JTA and so on; just as no out-of-the-box transparency
exists for JDBC -- a main vehicle to access databases from within a servlet --
the constructs within a servlet for all of the above technologies have to be
manually coded on a case-by-case basis. Nevertheless, the ability to embed the
whole spectrum of Java platform solutions on the client's behalf turns servlets
into a powerful middleware mechanism that extends the Java APIs to the Web.
It seems that both the servlets and the EJB technology are suitable platforms
for an enterprise application. Furthermore, they both seem suitable for
presentation-centric applications that do not require support for ''hard-core''
distributed services such as transactions, load balancing, persistence, state
management and message queuing, among others. The use of servlets might be even
more appropriate and certainly more straightforward. However, even though it is
possible to use servlets for truly distributed applications, such use would be
sub-optimal. The reason for this far-reaching statement will be clarified in
Part II of this article, in which we will compare these two technologies in more
detail. Stay tuned.