The WebSphere Application Server is
J2EE Certified. What is J2EE?
A few years ago, it became quite evident that the standard Java
development environment simply wasn’t equipped well enough to handle the needs
of a modern enterprise environment. While the Standard Development Kit (SDKÔ)
provided a solid foundation for Java development, it simply didn’t provide a
conducive environment for developing distributed, enterprise applications.
For that matter, it wasn’t that great at creating small
applications that would run on a handheld device like a PDA (Personal Data
Assistant) or a cell phone.
So, the powers that be broke the Java world into three distinct
segments:
F Java
2 Standard Edition (J2SEÔ)
F Java
2 Micro Edition (J2MEÔ)
F Java
2 Enterprise Edition (J2EEÔ)
What is J2SE?
The Java 2 Standard Edition, J2SE, is simply the latest
incarnation of the basic Java development and runtime environment that has been
available to developers since day one. J2SE is also referred to as, correctly
or not, the SDK (Standard Development Kit), JDK (Java Development Kit was the
former name) or even the JRE (Java Runtime Environment).
The J2SE allows developers to create basic and simple Java
applications that can run on any desktop computer.
J2SE applications do not support enterprise J2EE components such
as Servlets, EJBs and Java Server Pages (JSPs). Furthermore, J2SE doesn’t
provide facilities for developing small, compact applications that run well on
Palm Pilotsâ or
cell phones. The J2SE simply provides an effective environment for developing
desktop applications.
What is J2ME?
J2ME, the Java 2 Micro Edition, is a special Java development
environment that makes it easier to create applications that can be run on
small, handheld devices.
Figure 2-1
|
J2ME
Target Devices
|
|
È
Cell Phones
|
Ë
PDAs
|
Ç
Handheld Devices
|
Micro devices have a much smaller amount of memory and processor power at their
disposal than do desktop applications, so micro applications must have a much
smaller footprint. The Java 2 Micro Edition (J2ME) makes the development of
these types of applications possible, while at the same time, leveraging a
developer’s knowledge of normal Java application development.
What is J2EE?
Developing enterprise applications is a difficult and daunting
task. A typical enterprise application must interact with a variety of complex
data systems, including message queues, databases and people management
software.
They must also support a variety of different client types, such
as stand alone applications that run on a desktop computer, or applications
that use an Internet web browser as their user interface.
J2EE is the Java 2 Enterprise Edition, and it is designed to help
facilitate the development of sturdy, scalable and bulletproof enterprise
applications.
F J2EE
is a specification.
F J2EE is a
philosophy.
J2EE is a framework for building and deploying enterprise scale
applications.
J2EE is a specification managed by Sun Microsystems, although all of the big players in the Java
middle-tier market, such as WebLogic and IBM, contribute to the development and evolution of the spec.
The J2EE specification outlines how a developer should go about
developing an enterprise application, and it defines a variety of services that
a vendor, such as IBM, must implement if they want to advertise a J2EE certified
application server.
The WebSphere Application Server is IBM’s certified, J2EE runtime
environment.
J2EE is a complex monster, and any attempt to capture what J2EE
is must start by breaking it down into its three very distinct parts:
F The
components we create and subsequently deploy to a J2EE Application Server
F The
services a J2EE
certified Application Server will provide to our components
F The
protocols used by clients to interact with our J2EE components
What types of J2EE components can I
create and deploy?
Strictly speaking, there are two types of components that can be
created and deployed to an application server, although a variety of subtypes
exist, making the J2EE framework appear much more complicated than it really
is.
Servlets and EJBs are the
J2EE components we create and deploy to the WebSphere Application Server.
Servlets, and their close cousin, JSPs, are the J2EE components that
are used to handle Internet based requests. Servlets and JSPs will be the focus
of this chapter.
|
U
|
Stand
alone applications and applets are also J2EE components that run in J2EE containers, and can
take advantage of J2EE services, but only EJBs and Servlets are deployed
directly to the Application Server
|
What exactly are Servlets?
An application server must be capable of handling and responding
to requests that come in over the Internet. A Servlet is simply a Java based
component that handles web-based requests.
The purpose of a Servlet is to accept and process a web- based
request, and subsequently send a response back to the client. Since the client
is likely a person surfing the Internet, the response delivered to the client
usually takes the form of a web page.
“Servlets respond to web based requests.”
Servlets are popular because they are incredibly easy to
code. With only a little bit of a Java
background, anyone can code a Servlet and dive head first into the empty pool
know as server side development.
Just how easy is coding a
Java Servlet?
There are only two methods you really need to worry about when
coding a Servlet:
F the
doGet method
F the doPost method.
The doGet method of a Servlet is automatically called when a
client invokes your Servlet by clicking on a link, choosing a bookmark from
their list of favorites, or typing the name of your Servlet directly into the
address bar of a web browser.
The doPost method of a Servlet is usually invoked when a user fills out an
html form and clicks the submit button.
If a user is going to call your Servlet by clicking on a link,
you code the doGet method. If the user will
be filling out a form and sending data to the server, you code the doPost
method.
Choosing which of these two methods to code is one of the more
difficult parts of Servlet programming.
J
What parameters are passed to the
doPost or doGet method of a Servlet?
The doPost and doGet methods are passed two very important
objects:
F an
HttpServletRequest object
F an HttpServletResponse object
The HttpServletRequest,
a.k.a. request, and the HttpServletResponse,
a.k.a. response, make handling web based requests incredibly easy.
“Servlets are popular because Servlets are incredibly
easy to code.”
Anything you want to know, or for that matter, are allowed to
know about the client, comes through the request object. Get it? The
request object describes the request that has come in from the
client.
Anything you want to do to the client can be done through the response object. Get it? The response object allows you to
manage the response that gets sent back to the client.
Servlet programming really is that easy. Sure, there are a few method calls you have
to get familiar with, but with a bit of a Java background, getting up to speed
with Servlet programming will be a cinch.
Could you show me a simple Servlet?
We never like to muddy the waters with all sorts of Java code,
but in this case, an example is probably a worthwhile venture.
|
public class SampleServlet extends HttpServlet {
public void
doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,
ServletException
{
PrintWriter out =
response.getWriter();
out.print(“<HTML><BODY>”);
if
(request.getLocale().equals("en_ca"))
{
out.print("Let's go for a
Tim's, eh!!!");
}
else
{
out.print("See ya at
Starbucks.");
}
out.print(“</BODY></HTML>”);
}
}
|
What is a JavaBean?
Servlets use and delegate
to JavaBeans. A JavaBean is simply a reusable, logic component written in Java.
A JavaBean can perform business logic, interact with backend resources, or
simply act as a data transfer object.
JavaBeans are sometimes
referred to as POJOs, which stands for Plain Ordinary Java Object.
The following JavaBean is
simply a timer. It keeps track of the
time somebody invoked the start method, and then can calculate how much time
has elapsed when someone invokes the getElapsedTime( ) method.
|
public class
Timer implements Serializable
{
private long startTime;
public Timer()
{
startTime = 0;
}
public void start ()
{
startTime =
System.currentTimeMillis();
}
public long getElapsedTime ()
{
return
System.currentTimeMillis() – startTime;
}
}
|
Debriefing the
Servlet
In the preceding Servlet, the request object is used to see if
the client is Canadian. If the client
is indeed a Canuck, well, they probably really love Tim Horton's coffee. If the
client is not Canadian, the client probably does not appreciate good coffee,
and would likely settle for a Starbucks.
The request object is used to find out information about the
client making the request. In this case, the request object is used to
determine users Locale.
Using the response object, some delicious HTML is sent back to
the client and subsequently displayed in the clients browser.
Again, Servlet programming is easy. Anything you want to find out
about the client and their incoming request is in the HttpServletRequest object. Anything you are allowed to do to the
client is done through the HttpServletResponse object.
“Servlet programming is easy.”
So, with a little bit of a Java background, coding a Servlet and
using the request object to figure out what a user typed into a text field, or
finding out which radio button they selected is straight forward.
Furthermore, displaying text in a client’s web browser, or even
redirecting a client to a different web page, is accomplished fairly easily
through methods in the response object. From that point on, what a developer
does with a users request and the users response object is only limited by
their Java programming skills.
What can I do inside a doPost or
doGet method?
Do I really need to say this again?
Table 3-1
Methods of the HttpServletRequest and
HttpServletResponse
|
HttpServletRequest Methods
|
HttpServletResponse Methods
|
|
getCookies()
|
addCookie()
|
|
getLocale()
|
addHeader
|
|
getUserPrincipal()
|
sendError()
|
When coding a Servlet, anything you are allowed to know about the
client can be obtained through the request object. Anything you want to ‘do’ to the client you can be done through
the response object. All of this happens inside of a doPost or a doGet method.
|
G
|
You
will notice that the doPost or doGet method of a Servlet throws the IOException.
My
bank throws the same exception. They keep calling me up, telling me that I
owe them this, and I owe them that.
|
An Example of a Request-Response Cycle
Let’s take a look at a simple example of a request-response cycle
that might occur between a web-based client and the WebSphere Application
Server.
Let’s say you, as a developer, wanted to know which browser a
client was using. Maybe you were even wondering if the client was using a Palm
Pilot or a Nokia cell phone. Maybe you need to know which language the client
speaks. Where would you find this information? In the HttpServletRequest object of course!
And say you wanted to plant a cookie on a client machine, or
simply send some HTML back to be displayed in the client’s browser. How would
you do that? Well, you'd call some methods in the HttpServletResponse object, that’s how!
For the most part, the primary job of the Servlet is to inspect
the incoming request, and then figure out what kind of a response to send back
to the client.
Inspecting
the Request
From the request, we can find out what a user may have typed into
a given text field, what their preferred language is, and even which browser
they are using. The Servlet then uses
this information to make sure the request being made is indeed a valid
request.
If the request is indeed valid, the Servlet will execute the
appropriate business logic required to fulfill the request, and then figure out
what type of markup language and content should be sent back to the
client.
Generating
a Response
After handling a request, the Servlet must formulate a response
and subsequently send something handsome back to the user. After processing a
request, it is very important that we inform the user about the success,
failure, or overall status of their interaction with the application server.
This is the gist of handling the Servlet request-response cycle.
The
Challenge
The challenging part of developing Servlets is deciding what to
do between handling the request and formulating a response.
For example, the request object can tell you what a user has
typed into a couple of text fields, or which radio buttons a user has selected. What are you going to do with this
information?
“The complexity of your Servlets is only limited by your
Java programming skills.”
Perhaps you want to save the input to a database. Maybe you want to place some information
about the client’s request on a message queue.
Maybe you want to interact with an Enterprise Java Bean, which would
then require a JNDI lookup
and an interaction with the UserTransaction object. Crazy stuff for sure, but you can do it if you want to.
The point I’m trying to make is this: it is easy to get
information about a client from the request object, and it is even easier to
send a response back to the client using the response object. What you do between handling the request and
sending a response back to the client is only limited by your own creativity
and the extent of your Java programming skills.
Where does a Java Server Page (JSP) fit into this whole framework?
There are only two types of J2EE components we can write: EJBs and Servlets. This may comes as a bit of a shock, but a JSP is really just a
Servlet, although coded in a slightly different manner.
The SimpleServlet coded earlier had an ugly mix of HTML tags and Java. Optimally,
markup language and Java code should never be mixed together.
“A JSP is just a Servlet turned inside out.”
Servlets are intended to acts as controllers, and Java is used to
implement this control logic. However,
HTML tags get mixed in with the Java code if the Servlet also takes on the
responsibility of sending data back to the client.
Mixing Java and HTML within a single component creates a
maintainability nightmare, so as much as possible, we try to keep complex Java
logic in a Servlet, and have the generation of dynamic HTML factored out into a
JSP.
Is there anything you can do in a
JSP that you can’t do in a Servlet?
A JSP is just a Servlet that’s been turned inside out. A Servlet is Java code with a little bit of
HTML in it. A JSP file is mostly HTML
with a little bit of Java inside of it.
But there’s nothing you can do with a JSP that you can’t do with a
Servlet.
What does a JSP look
like?
Here is the previously viewed SimpleServlet turned into a JSP:
|
<HTML>
<BODY>
<%
if
(request.getLocale().equals("en_ca")) {
%>
Let's go
for a Tim's!!!
<%
}
else
{
%>
I guess we
have to settle for Starbucks.
<% } %>
</BODY> </HTML>
|
Mixing Java Code and HTML
It is unhandsome when we mix HTML tags and Java code together in our Servlets. It is equally unhandsome when we mix HTML
with Java code inside of our JSPs. A separation of responsibilities is
definitely in order.
While they are coded differently, at runtime, JSPs and Servlets
are two peas in a pod. JSP files are actually converted into Servlets when they are run on
the application server; as a result, all of the tweaking the web container does
to make your Servlets run so efficiently is implicitly available to your JSPs
as well.
What should I use, a Servlet or a
JSP?
To a question like that,
there really are no right answers. There are only wrong answers, and all we can
do is try not to get a wrong answer.
As a good rule of thumb, a Servlet should be used to initially
handle an incoming request and implement some control logic. This might include
validating user input and making sure a user is making a reasonable request.
A Java Server Page should
be used when you are mostly generating HTML. A JSP should only ever require a
minor amount of Java logic. This makes JSP files much easier to maintain.
“A JSP can do anything a Servlet can do”
Generally speaking, most applications have a Servlet handle the
incoming request, and then the Servlet forwards to a JSP to generate display
and subsequently send HTML back to the client.
Again, anything a Servlet can do a JSP can do, and vice-versa. In
fact, the only difference real between the two is how they're coded.
Servlets and JSPs sure don’t look
the same!
Even though they look different, when a client calls a JSP, the
Application Server actually calls on a special Servlet of its own that reads
the JSP, and subsequently creates a Java Servlet based on what is coded inside
the Java Server Page.
The Application Server
then compiles the code that it creates, and then the newly compiled Servlet is
loaded and run on the server. All JSP
files get turned into a Servlet at runtime.
|
¯
|
Since
it is actually a Servlet that turns the JSP into a Servlet, I often refer to
it as the BorgServlet, although the actual name IBM
uses is much less creative.
|
What exactly is an Enterprise Java Bean, EJB?
Let us establish one undeniable fact: enterprise programming is hard.
Sure, Servlets are superb at handling client requests, and Java
Server Pages are fabulous at generating markup for a client, but request-response
programming is not where Java developers earn their salt.
Java developers earn their salt by implementing some seriously
complicated business logic. Fiddling with a Servlet’s request and response
objects all day long won’t impress anybody.
Enterprise programming is hard, but EJBs make some of the
toughest parts of enterprise programming just a little bit easier.
What are the common challenges
enterprise developers encounter?
Enterprise programming is hard. In an enterprise environment,
there are a number of mission critical challenges that must be addressed and
implemented properly, otherwise applications will fail.
Some of the typical challenges that enterprise developers
encounter include:
Database Access:
How do we ensure that that data in our application is
completely, totally, 100% in sync with what is in the database? This is a
requirement of almost every enterprise application, but without an intimate
knowledge of how a database works, implementing database synchronization properly
is a significant challenge.
Transactional Updates:
If I'm updating three different databases in an ‘all or nothing’
type of scenario, and one of those database writes fails, how do I roll back
writes to the other two databases?
What if one of those databases is in Kalamazoo and two of them
are in Tuktoyaktuk? How do you maintain the transactional integrity of your updates?
Distributed Programming:
I'm in Gun Barrel, Texas, but I want users in Antigonish, Nova Scotia to remotely
invoke the methods in my Java components. How do I make a local component
accessible to remote applications?
Multithreading:
Multithreading remotely accessible components that must handle a
gargantuan load is a difficult and onerous task. How are you going to do it?
Secure Access:
You only want Double Agents to call one method of your JavaBean,
and only Secret Agents can call the other method. How ya gonna do it? With a
typical Java application, it’s almost impossible.
How do EJBs Make
Life Easier?
Database concurrency, distributed transactions, multithreading,
distributed programming and secure accesses are all issues our enterprise
applications must deal with.
If we have to deal with these issues alone, we’re going to be in
an ugly world of hurt. The good news is
that EJBs deal with these issues, and by dealing with them, they make
enterprise programming much, much easier.
So, how do EJBs work?
There is quite a bit going on inside an EJB.
To take care of things like security and transaction management, EJBs use special XML files called deployment
descriptors. The deployment
descriptor contains information about how the EJB, and its methods, should
behave at runtime. When WebSphere loads an EJB, it reads the associated
deployment descriptor and follows the instructions therein.
EJBs also implement a number of common design patterns, such as
the proxy, pooling and singleton patterns. EJBs are
designed well, and EJBs work well when used properly.
“Enterprise programming is hard”
Another interesting thing about an EJB is that unlike a regular
Java component, an EJB isn’t just one single file on the file system. An EJB is actually a collection of three or
more class files that work together to create a single, logical entity.
Let there be no mistake about it: EJBs have a learning curve associated with
them. Enterprise Java Beans are harder to write than a regular JavaBean or Java
component. But don’t fret. The payoffs make the learning curve well worth it.
Anyone who has a Java background can pick up EJB technology
relatively quickly. A few learning pains will result in a vast array of
programming gains.
What types of EJBs (Enterprise Java Beans) are there?
EJBs come in three different flavors:
F Session Beans
F Entity Beans
F Message Driven Beans
Let’s take a look at them one at a time.
What are Entity Beans?
Entity Beans represent an object-oriented bridge between your enterprise
application and your relational database.
“Entity Beans represent persistent data”
Entity beans are special Java components that represent persistent data.
When we say persistent data, we are usually speaking about data stored in a
database. Theoretically though, Entity Beans could map to
anything from data in a text file, to a serialized JavaBean on the file system.
Nevertheless, the vast majority of the time, your persistent data is stored in
a database.
An Entity Bean Example
Imagine you have a database containing a table named USER. This
USER table has columns that represent a users name, phone number, password and
email address. An entity bean, very creatively named UserEJB, could be created
that matches the USER table, and accordingly has properties that match the name
and data type of the data contained in that USER table.
Since an entity bean represents data in a database, if a
developer called setter methods such as setPassword("xyz123"), the
EJB promises to immediately update the underlying data in the database.
An entity bean represents your backend data, and the EJB
framework ensures that an entity bean is always 100% completely and totally in
sync, at all times, with the data in your database. That is the promise of the
EJB spec.
Accessing data is the flipside of updating data, but with an EJB,
the promise is the same: 100% synchronicity.
“The EJB promise is 100% synchronicity.”
When a developer calls a getter method on an EJB, such as
userEJB.getName(), the application would subsequently be given exclusive access
to the name field of that particular user in the database.
When you call a getter method on an EJB, the application server
absolutely guarantees that the returned information will be completely and
totally in sync with what is in the database. Achieving this end on your own by
hacking around with regular Java code would be hard, if not darned near
impossible. Accomplishing this with an entity bean is incredibly easy.
How does an entity bean
ensure transactional integrity?
I often get asked this question? The answer: I really don't know.
I think it's done through a collection of database locks, method
calls, and a little bit of Haitian Voodoo, but I’m not completely sure.
The fact is, I don't know, and I don't need to know. All I have
to worry about is writing the EJB.
All the underlying plumbing that makes these EJBs work is
implemented by a bunch of clever sausages at IBM that know far more about
database access and transaction management then I'll ever know. I’ll leave the infrastructure stuff up to
them. I’ll stick to coding these simple
little entity beans.
What is a CMP Entity Bean?
Entity beans come in two different flavors: Container Managed Persistence
(CMP) and Bean Managed Persistence (BMP)
Since most applications need to interact with persistent data,
and since most vendors want you to buy their application server, each vendor
has implemented a custom mechanism to easily create an entity bean that maps
directly to a database table and the subsequent columns contained in that
table.
Not only do these vendor-supplied components represent data
contained in a database, they have inherent knowledge about how to update the
database, retrieve data, and even create new rows in the database table, so
long as they are supplied with a unique primary key. These vendor-supplied
components are quite amazing, and remove much of the need to compose boring SQL statements or develop data components whose silly setters and
getters transactionally interact with a database.
“Vendor supplied entity beans are known as CMPs”
These vendor supplied entity beans are know as CMPs, or Container
Managed Persistence beans, because it is the vendors EJB container that
implements the persistence for us.
How does top down, bottom up, and meet in the middle mappings
differ?
Vendors provide many ways to create Container Managed Persistence
beans (CMPs), including:
F top
down
F bottom up
F meet in the middle
‘Bottoms-up’ occurs when you already have a database, and you
want to create EJBs based on your database tables.
Top down happens when you first create your EJBs and object
model, and want to have database tables created based upon that model.
With a top down mapping, tools such as WebSphere Studio Application Developer will
allow you to create EJB components first, and then the tool will generate SQL scripts that will create database tables based upon the components
you have coded.
Meet in the middle happens when your database administrators and
your application developers just can't agree on how to coordinate the
relational model with the object model. The developers go off and create EJBs.
The database admins go off and create their database. Then some poor shmuck has
to figure out how to bring the two parts together. In other words, the shmuck must meet the relational and object
models in the middle.
Meet in the middle allows Java developers to map EJBs that have
been created in isolation to database tables that already exist. This is
probably the most common type of EJB mapping we see in the industry.
What is a BMP Entity Bean?
A BMP is any
entity bean that isn't a CMP. That was easy. J
As was discussed earlier, Container Managed Persistence (CMP) beans relieve the developer
from having to write SQL code,
which Java developers are notoriously bad at doing.
With Bean Managed Persistence (BMP), the developer is burdened
with the responsibility of writing all of the SQL code required to update, delete, create and find data in our
underlying database tables. Basically, with a BMP, the developer has to do more
work, and God forefend, maybe even talk to a database person to help put
together some SQL statements.
Why would anyone want to use a BMP?
Creating BMPs is definitely a more involved process than having a
development tool create CMPs for you. Nevertheless, compelling reasons to use
BMPs do exist.
Your Database Doesn’t Support
Container Mapping
Depending upon your database, a CMP isn’t always an option. For example, WebSphere Studio Application
Developer only allows you to create CMPs for certain databases, although most
major databases are supported. However,
you might be in trouble if you’re using a special object oriented database, or
perhaps a database that doesn’t have the same market penetration as Oracle or
DB2.
Your Database is Far Too Complicated
Your database might be too complicated for the development tools
that make container-managed persistence possible.
If your database is filled with crazy joins, you have an
egregious amount of mango to mandarin relationships, and your ERD looks like a
map of the North American rail system, then I’m afraid that the conventionally
available CMP tools
won’t be much use to you. In a case
like this, you have to write your own crazy SQL code to interact with your crazy database - the development tools
simply won’t have anything to do with you.
Portability is an Issue
Another thing to think about is portability. Of course, if
you’re using DB2 and WebSphere, portability isn’t an issue, because IBM is the
best, and you would never want to leave them. But it is important to note,
despite an ongoing effort to standardize EJB development, one vendor’s CMPs are
a little bit different from that of another vendor. WebSphere CMPs won’t
necessarily port to a WebLogic server, although the latest incarnation of the CMP spec is indeed bridging that gap.
Assuming the SQL being used within them is fairly standard, BMPs will port from one
database to another with ease. Portability is more achievable with a BMP than a CMP.
Performance and Control
Generally, a CMP will perform faster than a BMP, especially if you’re going
from a WebSphere Application Server to a DB2 database. Yes, believe it or not,
those clever sausages at IBM know a lot more about efficiently connecting to a
DB2 database than you or I.
Furthermore, CMPs can take all sorts of shortcuts behind the
scenes that we simply don’t know about.
Vendors compete on who has got the most efficient application server,
and efficiently connecting to a backend database is a pretty big sales point.
CMPs are generally better at interacting with a database than BMPs.
Can I use CMPs and
BMPs at
the same time?
Choosing between CMPs and BMPs is not an all or nothing decision.
Container and Bean Managed Entity beans can coexist quite efficiently within the same application
server.
In fact, a creative use of inheritance and interfaces makes it
easy to interchange BMPs and CMPs. This would allow you to quickly create CMPs,
but seamlessly switch to BMPs in the future if the need ever arises.
What is better, a CMP or a
BMP?
I’m sure some would argue that BMPs, since you code them pretty
much from scratch, give you more control, and even though I suggest that CMPs
are faster than BMPs, others might argue that by implementing things like a
‘dirty bit’ pattern and performing some funky SQL magic, you could actually make BMPs more efficient than CMPs. That
may be true as well. The ability to
control database access in a BMP provides the opportunity for infinite refinement.
Nevertheless, the cost of any application is not how much it costs
to create, host, or get it deployed.
The biggest cost associated with an enterprise application is
maintaining it over time, and maintaining the optimized BMP code, written by the in-house super-genius after she’s left the
company to invigilate at MIT, might be insurmountable. CMPs are best if you can
use them.
CMPs are much easier to maintain that BMPs. Maintaining a
component with no code inside of it is the kind of task for which I’ll gladly
volunteer.
This brings us to another point – love them or hate them, CMPs do
provide a standard framework for mapping Java components to a back end
database, making object-oriented, transactional, database access possible. A common framework that is easy to learn,
and for that matter, easy to find a new hires that understands it, is a good
thing.
Use CMPs if you can. They will make your life easier in the long
run.
Should I have a one to one
relationship between Entity Beans
and database tables?
With top down and bottom up mappings, CMPs are incredibly easy to create. I can point my development tool at a
database and create hundreds of CMPs in a matter of minutes – one for every
table in the database. It’s just that
easy. In fact, it’s too easy.
Entity beans are resource intensive, and using them ‘willy-nilly’ will
ground your applications to a crawl.
“With EJBs, effective use is minimal
use.”
When you are using an entity bean, make sure you really, really,
really need the features an entity bean provides. These features include security, multithreaded access, and transactional integrity. Do not use Entity Beans just because you need a simple, object oriented relational
database component model.
“Entity Beans are often overkill.”
Frameworks like Hibernate and Java Data Objects (JDO) exist
because EJBs are often overkill when all you need is an object oriented
approach to database access. If you
don’t need all the features of an EJB when updating a database, look at some of
the alternatives to entity beans.
When it comes to EJBs,
effective use is minimal use. That should be the mantra of your enterprise
developers.
What is a Message Driven Bean, MDB?
Anxiously anticipated, and newly introduced with J2EE 1.3, is the
Message Driven Entity Bean (MDB).
Messaging is an important part of any enterprise applications.
Messaging allows an application to put information on a message queue, and be
assured that that information will be processed at some time in the foreseeable
future.
Essentially, message queues allow an application to implement
delayed processing. Delayed processing of messages is also known as asynchronous messaging.
How does asynchronous messaging work?
Have you ever placed an order over the Internet, been told that
your order has been processed, and then you don’t get an actual confirmation
email for about an hour or two?
When you placed your order, the website grabbed your order
information, which likely included your email address and credit card number,
and then shoved that information in a message, and plopped that message on a
message queue. When the application
server got a little bored, or at least when the workload died down a little bit, the application server grabbed your order
off the queue and processed it, thus the delay in getting your email confirmation.
That is asynchronous messaging in action.
By using a message queue, we can delay processing, while at the
same time, ensuring that a particular task will be transactionally performed.
Asynchronous messaging, which occurs when a message is placed on
a queue and a client does not need to wait for that message to be processed, is
an important part of any enterprise environment. Curiously though, J2EE has been fairly shy when it comes to providing
a framework that eases the burden of message-oriented programming.
Well, with WebSphere 5 and J2EE 1.3, we have message driven entity beans, MDBs, which
make reading messages off a queue much, much easier.
Message driven entity beans are a special type of Enterprise Java
Bean (EJB) that is designed to wait for messages to be dropped off on a message
queue, and then subsequently read those messages and react to the information
contained therein.
How do message driven beans compare
to the other Enterprise Java Beans?
In use, creation and deployment, a message driven bean is quite a
bit different from any other type of EJB. To be honest, I kinda cringe at the
fact that this snobbish little messaging component has been included under the
sacrosanct heading of EJB. However, I must be remiss and accept the wisdom of
those who created and contribute to the J2EE specification.
Messaging is an important part of almost every enterprise
environment, and until J2EE 1.3, the developer was responsible for reading
messages from a queue, and subsequently processing those messages.
To help standardize the way applications read asynchronous messages off a queue, and to stop the pissing contest between
developers who contended they had best implementation of messaging, J2EE
introduced the Message Driven Entity Bean (MDB).
Essentially, an MDB reads messages off a queue or topic, and then executes business
logic based on the contents of that message.
Quite often, the MDB just converts the message into a plain ordinary
Java object (POJO), and then passes that POJO
off to a Session Bean for further processing.
What is a Session Bean?
There are three types of Enterprise Java Beans:
F Entity Beans (BMPs and CMPs)
F Message Driven Beans
(MDBs)
F Session Beans
(Stateless and Stateful)
We have discussed entity and we have discussed message driven
beans. A session bean is anything that doesn’t fall into the two aforementioned
categories. J
A tongue in cheek definition for sure, but it is surprisingly
accurate. After all, message driven beans are tied to a message queue or topic.
An entity bean is bound to persistent data. A session bean is truly a free
spirit, entitled to do whatever the heck it wants.
When would you use a Session bean?
Session beans are important J2EE components, but before we diving
into the virtues of the session bean, let’s rehash the reasons why we would
want to use an EJB in the first place. EJBs are great because they provide:
F Remote
distribution
F Transaction management
F Multithreaded control
F Secure access down to
the method level
Now imagine we wanted to take advantage of all, or even just
some, of these great services, but we weren’t interested in persisting data to
a database, and we weren’t interested in reading messages off of a message
queue. What option would we have? Well,
we could use a Session bean!
Session beans come in two different flavors:
F Stateful Session Beans
F Stateless Session Beans
What is a Stateful Session Bean?
A stateful session bean is a session bean that maintains internal
data in the form of instance variables.
Furthermore, when a user creates a stateful session bean, the internal
properties of that bean are tied to the user that created it.
|
|
If
America was an EJB, it would be a stateful session bean. After all, it has fifty different states, 52 if
you include Canada and Mexico.
|
A simple stateful session bean might be a timer. If user logs into our website, we could
create a stateful timer that stores the time of first contact. The login time would represent the internal
state of the session bean.
Using our stateful session bean, any time our user requests a new
web page, we could query the stateful session bean and ask how long it has been
since the user logged in. Using higher
calculus, we could triangulate the elapsed time based on the current time and
the time the user first entered our site, which is stored in our TimerEJB. The timer would be a simple,
yet perfect, stateful session bean.
What is a Stateless Session Bean?
If you make eye contact with a session bean, and it is not a
stateful session bean, then you are staring deep into the soul of a
stateless session bean.
A stateless session bean is a session bean that doesn’t posses
any internal state.
From a Java programming standpoint, a stateless session bean doesn’t
contain any meaningful instance variables.
“A stateless session bean has no instance variables”
From a users point of view, one instance of a stateless session
bean is identical to any another instance of the same stateless session bean.
Since there is no internal state to differentiate one stateless session bean
from another, a client cannot tell the difference between one and another..
A stateless session bean does have methods. A stateless session bean ‘does stuff,’ but
it doesn’t necessarily keep track of what it has done from one method
invocation to another.
You could think of a stateless session bean as a ‘task oriented’
component that can do something important for us, and when it is done, it is
ready to do the same thing again for someone else. A stateless session bean doesn’t discriminate.
When would I use a stateless
session bean?
On the surface, a stateless session bean might appear to be
rather useless. After all, it doesn’t
interact with a database, it doesn’t read from a message queue, and it doesn’t
even possess internal state; and internal state is what makes typical Java
components interesting.
“Stateless session beans don’t discriminate.”
Quire contrary to first impressions, stateless session beans are
the most important, most useful and most exciting Enterprise JavaBeans our
developers will create.
Session beans might not have any internal state, but they do have
methods that can invoke any number of objects that do indeed possess internal
state, and that is exactly what stateless session beans usually do.
A Stateless Session Bean Scenario
Imagine your application had a requirement that it must be able
to update three different databases in an all or nothing type of transaction.
Database One might
represent a users savings account, for which the user is transferring out $100.
Database Two represents the users checking account, which the
user is transferring in $100. The money
being transferred into the checking account is the money transferred out of the
savings account.
And when the transfer into the checking account is complete, and
the transfer out of the savings account is complete, a third database keeps
track of the transaction, so that the user can be charged exorbitant banking
fees at the end of the month.
How could we coordinate this simultaneous and transactional
update of three different databases?
How could we ensure that if one database write fails, all three database
writes are rolled back? After all, people get upset when money is transferred
out of one account, and not subsequently transferred into the other. People are picky that way.
To control the transactional update of three different databases,
we could simply create a stateless session bean with a single method that calls
on three different entity beans.
We could tell this one method, by configuring its deployment
descriptor, to run within the scope of a
transaction, so if any database writes fail, all the database writes will be
written back.
We could even slap a security attribute on the method as well so that only certain users can
call it.
Furthermore, by using an
inherently multithreaded EBJ, we know that concurrent access won’t be a problem. After all, that is what a J2EE compliant
application server promises us when we use EJBs.
We can also invoke the session bean’s method remotely, since EJBs
implicitly implement remote distribution through remotely invokable interfaces.
Stateless session beans become the glue that holds the whole EJB
horse together.
|