Java J2EE Intro Course Book v2
Java J2EE Intro Course Book v2
An Introduction
Course Companion
Contents
CONTENTS 2
Background to Java 6
Java Applets 7
Java Applications 8
Server Side Java 9
Summary 9
Java Variants 10
The Java Development Kit 10
Evolution of the SDK 11
Java Help 12
The Key Java Features 13
Platform Independence 13
The Java Virtual Machine 13
Graphical User Interfaces 14
The “AWT” 15
Swing to the Rescue 16
A Swing GUI 17
Multi Threading 18
Java Multithreading 19
Multithreading Example 19
Running the Multiple Threads 20
The Output 20
Error Handling 21
Exception Handling Example 22
Object Orientation 23
Java Garbage Collection 23
Java Applets 24
Databases in Java 24
Summary 24
Language 3: C# (C-Sharp) 29
VB vs Java 29
C++ vs Java 30
C# vs Java 30
Microsoft .NET 31
Summary 31
JAVA PERFORMANCE 32
Java Performance 32
Why Should Java be Slow? 32
Slow Java 32
Demo and Benchmarks 33
Demo 33
Benchmark Summary 34
Native Code Compilers 34
Summary 34
INTRODUCING J2EE 35
What is J2EE? 35
Two-Tier Architecture 35
Two-Tier Architectures: Disadvantages 36
The Three Tier Model 37
Application Servers 37
The J2EE Standard 38
J2EE Components 38
Java Servlets 38
Java Server Pages (JSP) 39
Enterprise Java Beans (EJBs) 39
The J2EE Architecture 39
Concrete Example – A Warehouse 40
Summary 41
Java Beans 53
The Purpose of Java Beans 53
Enterprise Java Beans 54
EJB’s Are: 54
EJB’s are Persistent 54
EJB’s are Transaction Aware 55
Place Order Example 55
EJB’s are Distributed 56
EJB’s are Multithreaded 56
Types of EJB 57
Entity Beans 57
J2EE Design Patterns 58
Example Design Pattern 58
Design Problem 59
Design Solution 59
EJB Summary 60
COURSE SUMMARY 65
Java Problems 65
BIBLIOGRAPHY 67
Introduction
The Purpose of this Book
This book accompanies the course “An Introduction to Java and J2EE”. Aimed at a
general audience of both technical and non-technical people, the course describes the
principles of the Java language – where it came from, why it is popular and what it
can offer. The second half of the course describes the Java Enterprise Edition – a
framework for building large scale Enterprise applications using the standard Java
language.
The course does not cover the technical details behind Java and J2EE, in particular
how to write programs in Java. For these details, see the in-depth Programming in
Java courses.
If you’re a project manager on a new Java project, you may find some of our
Standard
suggestions in to boxes like this one. They’re only suggestions and may not
work for your project, but they are guidelines that we have found to be valuable
on other projects.
Chapter 1
The History of Java
Background to Java1
Back in the very early 1990’s a team of engineers were set up at Sun Microsystems to
pre-empt the “next big thing in computing”. Led by legendary Sun programmer James
Gosling, the team decided to concentrate their efforts on embedded electronic devices.
Given the prevalence of micro chips in TV’s, washing machines, remote controls and
so on, the team attempted to build a handheld device (their prototype was called “*7”)
capable of a wide variety of household tasks.
Which programming language would they use to program these electronic devices?
C++ could well have been the language of choice for Gosling’s team. C++ is based on
the decades old C language, and C has a proud tradition in the embedded systems
arena. At the time (perhaps the same is still true today), C++ was the most popular
programming language2 and by adopting this language for their devices, they would
be guaranteed a large and ready made community of engineers to program for their
products.
However (as we will see later), C++ is a very difficult language to master. It is very
easy to write C++ programs that may appear to work perfectly but which are in fact
bug ridden and unreliable. C++ gives the programmer a lot of power and freedom, and
while this power can be harnessed by experienced programmers, in the hands of less
competent engineers, disasters are commonplace.3
Gosling realised that a safer, more straightforward replacement for C++ was required
– and if the replacement could look a bit like C++, then so much the better for
persuading existing C++ coders to cross over to the new language.
1
See http://www.wired.com/wired/archive/3.12/java.saga.html for an excellent commentary on the
inception of Java
2
Cobol is probably in heavier use, but of the “modern” languages, C++ would have been the language
of choice for many software engineers
3
See reference [7] and read the details of the London Ambulance service fiasco – one source of the
problem was a C++ memory leak
The new language was codenamed Oak, and was quickly put together by Gosling and
his team (much of the language had already been created by Gosling, at home in his
spare time!). The language was subsequently renamed Java when it was realised that
another language called Oak already exists. Java isn’t an acronym by the way – it was
named after the team’s favourite coffee!
To cut a long story short, the “*7” venture was initially a failure. The take up of the
technology was slow and the group failed to win any significant business.
Meanwhile, the World Wide Web had been taking off dramatically and was causing
much excitement in the industry (and beyond the industry too – at the time there was
plenty of talk about the “Information Superhighway” in the media). Initially, the web
was a fairly static place – lots of simple text documents linked together. Web
visionaries craved interactivity – would it be possible one day to play games on the
web, or to view a company’s products, and order them, via the web?
The internet had never been considered relevant to Java during its design; but by
accident all of the design goals of Java – the ones that Gosling had observed to make
his language suitable for electronic devices - were directly applicable to the world
wide web. Java programs are designed not to crash – essential for the web. Java
programs are designed to run on any hardware – again, essential, given that users of
many different types of hardware use the web.
Gosling’s team changed tack, and in about 1995, they began to apply Java to the
internet. The potential of the language was quickly recognised by the internet
community and a mass of hype and excitement began to build up around Java. In
1995 and 1996, Java was definitely the hottest property in IT; the attention centred
around the idea of running Java Applets inside web browsers…
Java Applets
A Java Applet is a small Java application (Application-let), and is essentially a
graphical Java program that can run inside a web page.
• They will run on any browser (as long as the browser supports applets; the latest
versions of IE and Netscape do). They will also run on any platform, regardless of
whether the user is running on a PC, Mac, Sun Workstation, whatever.
• The biggest advantage of an applet is that they are dynamic. They can be
embedded into the static text of a web page and they can do things; the user can
interact with them. The example in Figure 1 is a fairly simple calendar, but
technically an Applet can be as complex as the programmer’s imagination allows.
• A serious concern in the early days of the web was safety. Given that an applet is
essentially a piece of software, how do we know that an Applet isn’t malicious?
For example, the calendar Applet could be secretly deleting all the files on our
hard disk, or it could be sending salacious emails to everyone in our email address
list.
Thankfully, Java addressed these concerns very well indeed. Users can be fairly
sure that an Applet is not capable of doing anything nasty or unwelcome – we will
look at Java security later on in the course.
All of the above is all very well, but Applets also suffer from some serious problems:
• Firstly, Applets are very slow to download. Well, they’re not that bad – the files
are relatively small, but an Applet that does anything vaguely interesting is
probably going to be too big to download comfortably using a standard modem.
Broadband internet wasn’t available back in 1996!
• Finally, many Applets look fairly shabby. This isn’t generally because the
programmers of the Applet are incompetent; it is more because the graphical
features supported by Applets are desperately limited.
In the early days of Java, there was a proliferation of cheap and nasty Java Applets all
over the web – usually doing things like small animations. It is fair to say that many
people still believe that Java is only capable of writing poor quality eye-candy on web
pages…
Java Applications
… but Java has always been capable of building full blown Applications running
outside web browsers. Certainly, the early releases of Java lacked some of the features
4
These restrictions can be circumnavigated these days –but not when applets were becoming popular
required to build very serious applications, but by version 1.2 of Java (released in late
1998), Java is now considered to be a full blown “serious” language.
Java still may not be suitable for writing real time safety critical systems (this is open
to debate, we won’t comment here), and certainly Java won’t be suitable for writing
low-level applications such as new Operating Systems. Other than these areas, Java
should be able to compete with any other language. We will compare Java to other
languages in a later chapter.
Server-side Java was evolving in many different directions until the whole concept
was formalised by J2EE (Java Enterprise Edition), which we will explore in detail in
the second half of this course.
Summary
• Java was originally designed as a language for writing small, embedded
applications on electronic devices
• Java became the first “internet” language in 1995-96; Java Applets were hot
technology
• However, Java is a very well designed language and is now being exploited to
build full blown applications
Chapter 2
Java Software Development
In this session, we will look at the main features of Java Software Development, and
what makes the language so well designed. We are not going to look at the “server
side” Java just yet – but almost everything in this chapter is relevant when developing
Java server applications as well.
Java Variants
Many newcomers to Java find the different variations of Java to be very confusing.
Before we set out, we’ll define the three major variants of Java. We’ll explore two of
them on this course:
• J2SE stands for “Java 2, Standard Edition” and is basically classic Java. Don’t let
the “Standard” phrase deceive you; J2SE is huge. It can be thought of as a
combination of the programming language itself, all the tools required to build
Java applications, and a set of libraries (we’ll look at these shortly).
• J2ME stands for “Java 2 Micro Edition”. This is a heavily cut down version of
Java, designed to enable Java to run on very small embedded devices such as
WAP telephones. It is exactly the same language as J2SE – it is just the libraries
that have been restricted in their scope. We will not discuss J2ME further on this
course, but you can check www.java.sun.com/j2me for more details
• J2EE stands for “Java 2 Enterprise Edition”, and provides the tools and libraries
necessary to extend Java into the heavyweight server side technologies. Again, the
language is exactly the same as J2SE and in fact J2EE is a strict superset of J2SE
– there is no overlap. So if your engineers are using J2EE, they are actually using
a combination of J2SE and J2EE. You cannot program J2EE applications without
being a good J2SE engineer first. We will look at J2EE in the second half of the
course.
So, the core of the language is easy to learn - however, the strength and power of Java
(and also its complexity) comes from the vast class library that is supplied alongside
the core Java language. In this chapter we will look at the main features of the
language and the library, and see how they help a software development.
The Java Development Kit (SDK) is Sun’s name for the combination of the
programming language and a collection of libraries providing a rich source of pre-
written functionality to the programmer. The SDK is free to download from the Sun
website at www.java.sun.com.
The library prevents the need to “reinvent the wheel” on our software developments.
If you need to (for example) write a program that uses Networking, the networking
functionality is provided as part of the class library. Similarly for Graphics, File
Input/Output, Database Programming and Security. Support is even provided for areas
such as Cryptography, File Compression, Multimedia – there are far too many areas
to list5.
With some other languages, such libraries have to be purchased from third parties –
apart from the cost, this of course means vendor lock-in and your programmers
writing non-standard code. With Java, it is all essentially part of the standard
language.
Since then, subsequent versions of Java (which are released every 18 months or so)
have added more and more features without fundamentally affecting the core
language. Version 1.3 was released in May 2000, and the latest (at the time of writing)
is 1.4 which emerged in late 2001.
Java programs are backwards compatible; if you upgrade from (say) version 1.2 to
version 1.4, then your programs should still compile. If the Java designers decide to
remove something from the class library, then your programs will probably still
compile but your engineers will receive warnings from the compiler called
deprecations. These warning indicate that although the engineer can get away with
using the feature in the short term, they should reengineer their code to avoid using
the removed features as soon as possible.
Confusingly, Versions 1.2 and onwards are referred to as “The Java 2 Platform”. This
was a bit of a marketing trick by Sun to indicate that Java 1.2 was a major
improvement on what had gone before.
5
The SDK comes with a complete set of documentation describing every aspect of the library.
Although these documents are difficult to read for newcomers to the language, experienced Java
programmers can often pick up new areas of library with little or no training.
Java Help
There are thousands of Java Classes available in the standard Java Class Library (a
class is basically a Java Module; all of your engineers programs will be constructed
using classes).
How can we deal with the complexity of thousands of classes? Thankfully, Java
provides a comprehensive help system. Documentation is available for every single
Java Class in the Library. This documentation can be a bit frightening for the
newcomer to Java, but a programmer with a reasonable amount of experience soon
becomes accustomed to the system.
Interestingly (and often overlooked) is that your project can also automatically
generate help files for your own custom built classes – a very valuable project
resource. We’ll see how this is done later (see “The Javadoc Tool”, page 62).
Platform Independence
Arguably, this is the key feature of the language. Until the advent of Java, almost all
programming languages would produce code that could only run on one platform (ie
type of computer). A program written for Windows would definitely not run on
Solaris or Macintosh, for example.
Java was designed with platform independence in mind from the start, from its early
days as a language for writing programs embedded into set top boxes. The team
developing Java realised that each set top box manufacturer would use a different
operating system, so this feature would be crucial to its success.
Java takes a different approach. Instead of converting the program into a series of
instructions specific to a particular machine, the compiler converts the program into a
series of platform independent instructions (Sun call these Bytecodes).
So, Java programs are converted into bytecodes. What happens to these bytecodes?
Well, the person running the program feeds the bytecodes into a tool called a Virtual
Machine6. The Virtual Machine reads the bytecodes and converts them into the native
instructions that the particular platform understands.
This simple trick means that the bytecodes produced by a programmer can be run on
any computer, providing a Virtual Machine exists for that computer. Since Virtual
Machines have been produced for most common platforms (Windows, Linux, Solaris,
Macintosh OS X), we can safely say that a Java Program is truly portable.
6
Virtual machines are prewritten pieces of software provided by a vendor. Sun produce one as part of
the SDK, but there are other implementations provided by other suppliers too.
Java
Compiler Bytecodes JVM
Source
Design time
Native
Runtime Machine
Code
Is Java really portable? Well, there are a couple of catches. Shortly we’ll look at
Java’s Graphical and Multithreading capabilities – these two areas are difficult to
make portable (each platform has its own way of doing graphics – compare a
Macintosh user interface with a Windows one!), and problems can arise in these areas.
Generally, though, everything should be ok. However, the advice is:
If you are producing Java software which you intend your customers to run on
different machines, make sure you extensively test your software on all target
platforms.
Perhaps the biggest challenge in achieving this was the problem of platform
independence. GUI’s on different machines, whilst sharing features in common,
usually have marked differences…
So how can we write a platform independent program that will look the same and
behave in the same way on different machines?
The “AWT”
Sun’s first attempt at a solution was the Abstract Windowing Toolkit, or AWT for
short. Here, Sun identified a common set of Components – graphical elements that
appear on all platforms, regardless of the operating system. For example, Buttons,
Menu Items, Scroll Bars, Text Boxes and Labels were some of the common
components.
When a Java Programmer writes an application using the AWT, they construct the
GUI using these AWT components. For example, they might request a button with the
word “Exit” written on it. The Java Virtual Machine takes that request and asks the
underlying operating system to draw a native button.
This simplistic solution had many problems. First of all, it was very difficult for Sun
to produce bug free implementations of the AWT for every single platform. Secondly,
because the AWT could only feature components that are present in every single
platform, the range of AWT was very limited indeed (components such as dividers,
slides, spin buttons and like were absent).
Perhaps more importantly, the look and feel of an AWT GUI is a little cheap and
nasty; see the example in Figure 6 – this is a typical example of an AWT interface.
• Present a Window
It is safe to say that all graphical operating systems should be able to fulfil the above.
Now, when a programmer requests (say) a button, Swing will draw the button, from
scratch, using pixels on a blank area of the window.
This clever technique means that Swing is able to support almost any conceivable
graphical component, even if the operating system you are running on doesn’t really
support it.
Swing was just the working title for this system; the real name for it is the “Java
Foundation Classes” or “JFC”, but somehow the name “Swing” has stuck. Sometimes
you will hear to it referred to as JFC, but Swing is the common term. By the way, as
with the name Java, there is no significance in the name. It’s just another “cool” word
these crazy Americans came up with. Something to do with Jazz I think…
A Swing GUI
As an example, here is a screenshot from a simple Swing application (this is a horse
racing game). As you can see, all of the features you would expect to see from a
standard windows application are present:
A very interesting feature of Swing is that the way the GUI is presented can be
switched by the programmer. Recall that the buttons, text boxes, lists, menus etc are
not being drawn by the operating system – it is Java that is laboriously drawing all of
these components itself (and as you can see from Figure 7, Swing aims to make these
emulated components look like the real ones). Since it is Java that is determining what
these components look like, it is a fairly simple job for Swing to draw them in a
slightly different way. As such, Swing allows you to choose from a set of predefined
Look and Feels.
The “System Look and Feel” is a look and feel that emulates the look and feel of the
operating system you are running on. In Figure 7, we are running on Windows and we
are using the Windows Look and Feel. If we ran the same application on a Mac7, then
the Macintosh Look and Feel would be adopted instead.
7
Remember – we can do this, because Java programs are platform independent and portable
The “Metal Look and Feel” is a look and feel provided by Sun in an attempt to
produce a “platform independent” look and feel. The benefit of using this look and
feel is that your application will look the same regardless of what platform you are
running on. The drawback is that your users might be a bit confused, because it won’t
look like a regular application. Here is Figure 7 redrawn using the Metal look and
feel:
As you can see, everything is there as before, but presented in a very different way.
Only one line of code was changed to make this happen.
A third look and feel, the “Open Look” look and feel, is provided – this look and feel
emulates the Unix type of look and feel.
Multi Threading
Every program we write is trying to solve a real world problem; whether we are trying
to predict the weather using mathematical algorithms, or trying to provide an on-line
shopping facility, the whole point of writing computer programs is to solve problems
that exist in the real world.
Unfortunately, computers are naturally and inherently (simply due to the way they
were originally designed decades ago) poor at doing more than one thing at a time.
Computers tend to churn through instructions, monotonously, one at a time. But the
real world doesn’t work like that – things happen concurrently.
In a defence system, we must be able to fire torpedoes whilst the commander is still
able to track the progress of targets on the screen (it would be a disaster otherwise).
Similarly, in an on line shopping system, we must allow two customers to view the
catalogue and order goods at the same time – if we could only service one customer at
a time, our sales would be adversely affected.
Java Multithreading
Java, however, provides Multi-Threading as part of the standard language, and,
relatively speaking, it is easy for a programmer to write a multi threaded program.
However, even with Java’s excellent support for multi-tasking, it is still a minefield. It
is very easy, for example, to write programs that can “dead lock” (this is when one
task in the program has to wait for the other task to complete and hand over some
results – but at the same time, the second task has to stop and wait for the first task to
do something!). This isn’t because Java is poor at multitasking; it is a simple fact that
designing multi threaded programs in any language is much harder and requires a
higher skill level than single threaded programs.
If you are running a project that is likely to employ multithreading, invest in a good
thread analyser tool – it will save you a fortune in the long run.
Multithreading Example
Here is a simple Java program that is capable of printing out the numbers from 1 to
500. Don’t worry about the Java syntax; the code in the “run” block is the code that
will run in parallel with whatever else is happening in the system; the code near the
top is simple plumbing to make the threading happen:
The Output
Here is the output from a run of the program where two versions of the code are
running concurrently:
…
118
119
120
121
122
123
124
125
1
126
2
127
3
128
4
129
5
130
6
131
7
132
…
Interestingly, the program outputs 125 consecutive numbers, and then the second
thread starts to output its numbers. From that point onwards, the two threads are
interwoven – one number outputted from each thread in turn.
The 125 consecutive numbers from thread 1 happened because thread 2 was busy
starting itself up while thread 1 had stolen a head start. Multitasking is generally
unpredictable – we could not have predicted that this would have happened, and we
certainly cannot guarantee that the same thing will happen on a future run. It is
entirely possible that next time around, 134 consecutive numbers are output followed
by a block of 4 from thread 2, and so on. It is just this sort of problem that makes
working with threads a difficult job.
Error Handling
Java features a mechanism known as Exception-Handling to allow the programmers
to deal with errors (and unexpected situations) in an elegant way. This mechanism
first became popular in the early 80’s with the Ada programming language. Designed
for defence systems, Ada required strong error trapping capabilities, so the language
enforced tight controls on the programmer.
Java has copied the idea behind the system (and has even strengthened it slightly).
This means that your programmers are forced to deal with any errors that can arise in
your system.
DatabaseDriver.connectToDatabase ("employees");
However, Java will refuse to even let the program run. Why?
Well, in this example, the code behind connectToDatabase might raise an error – for
example if the database is not available for some reason. Since this line of code might
throw an error, Java insists that the programmer provides some code to handle the
problem if and when it arises.
Until the programmer does this, the program will not even run!
The mechanism the programmer must use is called a try…catch block. The full
details of this are beyond the scope of this course, but basically the programmer must
indicate which line of code might throw an error (the try), and then in a separate
block tell Java what to do should something go wrong (the catch). Here’s what the
corrected program would look like:
try {
DatabaseDriver.connectToDatabase ("employees");
}
catch (Exception e) {
// deal with the problem, if it happens
}
So, Java will run the “connectToDatabase” call – if all goes well, then fine. But if
something goes wrong, it will run the code in the catch block. The programmer must
do something sensible here – correct the error, warn the user, shut the system down,
whatever.
Project Standard
One slight catch here – a lazy programmer could just put nothing in the
catch block, and Java won’t mind. This is very poor programming
practice that is justified in just a small number of cases. A good project
standard would be “no empty catch blocks”.
8
This example doesn’t use 100% real Java code; it has been simplified to get a point across. For full
technical details of the exception mechanism, see the full Ariadne Java Fundamentals Course.
Object Orientation
Java is what is known as an Object Oriented (“OO”) programming language. Object
Orientation is a different approach to the classic “functional” or “structured” method
of software development which “older” languages such as C, Cobol and Fortran
support.
A full description of Object Orientation is beyond the scope of this single day course
(see reference [1] for a downloadable e-book from Ariadne Training for a much more
detailed treatment), but we’ll try to describe the “high level” view of OO.
Basically, in OO, instead of creating functions and breaking the tasks our system has
to perform into smaller and smaller functions, we look at the real world problem we
are trying to solve, and identify the Objects that are present in the problem. For
example, in an e-commerce development, the objects might be Customer, Shopping
Cart and Credit Card.
The designers and programmers will then represent these real world objects in the
solution – and Java provides all the necessary tools to allow these objects to be
represented in the code.
One of the key benefits of following OO is that the “gap” between the problem and
the solution (requirements and code) is much smaller; hopefully then the eventual
code should be easier to understand and modify.
The real problem with OO is that there is still a lack of true understanding of Object
Orientation – it is certainly difficult to learn at first. Designing real OO systems is a
very valuable skill and OO does not provide a “silver bullet” to solve all problems.
Java is a full OO language, and if you are not writing true Object Oriented code in
Java, you are essentially wasting much of the power and elegance of the language.
If the programmer forgets, then a memory leak has been created. This means that the
operating system thinks the memory is still in use by the program, and the operating
system will not use that area of memory. This situation will continue even after the
application has terminated.
Think how serious this is if your application is running on a server. Your application
will probably need to run continuously for weeks on end. If the memory is slowly
being leaked by your application, eventually, the server will crash!
Thankfully, Java programmers never (or rarely) need to worry about memory leaks. A
process known as “Garbage Collection” regularly checks the program for unused
memory; when unused memory is found, the memory is returned to the operating
system.
If you are cross training existing C++ programmers into Java roles, they will hate this
– even though it is a very useful feature. The reason is that C++ programmers (good
ones) keep the problem of memory leakage at the forefront of their minds at all times
– it is difficult to “unlearn”!
Java Applets
A final word on Java Applets – we have discussed them already in previous sessions.
Applets can be written using any version of Java – but, the browsers only support a
limited range of Java versions. Users running Internet Explorer version 5, for example
(a very large percentage of the internet population, at the time of writing) will not be
able run Java 1.4 applets.
The solution to this problem is provided by Sun in the form of a “Java Plug In” – this
can be downloaded by the user from Sun, and the functionality of the web browser is
extended to cover the latest version of Java. The flaw in this idea is that the process
requires operator intervention (they will have to agree to the download and plug in
taking place), and worse, it will take a long time for the plug in to download.
We think it is fair to say that technologies such as Flash currently have the upper hand
over Java.
Databases in Java
Interfacing to relational database technology is important in any language, and
thankfully Java provides the necessary tools to enable this as part of the language. The
technology is called JDBC, or “Java Database Connectivity”.
As long as the programmer knows and understands SQL, then connecting to databases
and manipulating the database is easy in Java.
The database you are connecting to must support JDBC, or alternatively, Java can talk
to an ODBC9 compliant database through an inbuilt Java tool called an “ODBC/JDBC
bridge”.
Summary
• Java provides a wide variety of features as part of the standard language
9
A standard for connecting to relational databases; most databases will support it
It is platform independent
Chapter 3
Java vs Other Languages
In this chapter, we will briefly compare Java to other popular programming languages
Note that we won’t explore languages such as Pascal, Cobol and Fortran in this book.
Although these languages are still in very common use (and Cobol is perhaps the most
widely used language of all), their use is certainly in decline and they are obsolescent.
Although we promised at the outset to avoid as much code as possible, we will even
force you to debug a “working” C++ application in this session!
When faced with a choice of language for an application development, the major
choices these days are probably:
• Java
• C or C++
• Visual Basic
• C#
Other languages such as ASP and JavaScript are popular, but these are niche
languages lacking the general purpose uses of the languages above. JavaScript is a
script language that allows some dynamic behaviour to happen inside a web browser –
it has absolutely no relation to Java at all! ASP is a Microsoft language enabling
server side behaviour to be programmed in a HTML-like form – we’ll be discussing
the Java version of this, JSP, in a later session.
First of all, we’ll look at VB, C++ and C# in turn and discuss the features of each,
before we compare them with Java.
language as being a toy language for unskilled programmers, but the truth is that as
VB has evolved, it has become a serious programming language, and one that is now
fully object oriented.
Despite the serious nature of VB, it is still arguably much easier to learn than Java,
and it is certainly easier to use than C++. The modern feel of the language is
completed by its central paradigm – applications are constructed using components,
small, simple and reusable modules.
An Example VB Program
You lecturer will now expertly build a full blown windows application before your
very eyes in just a couple of minutes…
Language 2: C / C++
C is a language that can be traced back to the 1970’s and has a long heritage as a
programming language. C++ dates from the early 1980’s, and is an extension to the C
language (you can write pure C programs using C++; C++ is a strict superset to C).
The extensions revolve around Object Orientation (and a few other minor things); so
C++ and Java can both be considered Object Oriented languages (see “Object
Orientation”, page 23).
It is a very widely used language; most people who have used a computer have had
some interaction with C++ - Windows is written in C++ and Windows 95 was 30
millions lines of it!
Unlike VB, C++ is not owned by any organisation in particular, although Bjarne
Stroustrop created the language at Bell Labs. Many compilers exist for C++ and in
theory, an organisation implementing a C++ project are able to switch compilers at
will (in practice, however, many variants of C++ have evolved, and so this theory
doesn’t hold true). Visual C++ is Microsoft’s version of a C++ compiler, and while
their tool allows close integration with the windows platform, it isn’t a special version
of C++.
It is a very popular language with programmers; it is much deeper than Visual Basic
and basically, you can do anything you like in C++ - the power is in the hands of the
programmer.
C and C++ are both very terse languages indeed. Code written in either language is
very, very difficult to read and understand (this depends on the skill of the author, but
generally speaking, this is usually true). It is also difficult to learn – an average one
week C++ course could never bring a programmer to the same standard of
programming as a one week Java or VB course – for example, building GUI’s would
be out of the question as there would be much ground to cover first.
The biggest (general) advantage to C++? It generates very fast code. It is potentially
the fastest code you can get without actually writing assembler or machine code (no
chance of that these days).
Recall earlier on in the course we said that the Oak team, James Gosling et al (Page 6)
considered C++ as their language of choice for their electronic devices. One of the
reasons they rejected the idea was the potential for serious errors in C++ causing run
time crashes (not desirable in an embedded device). Here’s an example:
int square_array[10];
int count;
for (count = 1; count <= 10; count++)
square_array[count] = count*count;
Will the program run? Your lecturer will give a demo of the program. Your job is to
give the program a thumbs up or thumbs down, based on the demo of the program,
and your code inspection.
This space is provided to make your own notes about the debugging session:
Food for thought – that’s two lines of executable code. Now imagine the kinds of
problems you’ll get with a couple of million!
Language 3: C# (C-Sharp)
C# is another language designed by Microsoft. At the time of writing it is a fledgling
language and reports of use in the field are a little thin on the ground at the moment.
It is possible that there are legal rather than technical reasons for the development of
this language; we will avoid discussing these reasons here, and instead look at the
features of the language.
In fact, the main feature of C# transcends the language itself. It is part of the new
Microsoft .NET framework, which we will look at later. One of the main features of
.NET is that any language can be used as part of the framework. Java could not be
included (for legal reasons), and this is one of the reasons that C# was invented by
Microsoft – as a Java replacement.
VB vs Java
Visual Basic is clearly stronger at the production of graphical user interfaces. Swing
interfaces can be written using pure Java code (time consuming and difficult), or
using a tool – but still the tools are a little immature and not particularly easy to use.
VB has always provided the tools to build interfaces, and as we saw earlier, the tools
are easy to use and stable.
Visual Basic is definitely an easier language to learn and implement than Java. The
scope of VB is more restricted however; if you are building small applications on
Windows platforms then VB is a leading choice. Java, whilst being more complex, is
able to handle a much larger range of tasks than VB.
Visual Basic is only supplied by one manufacturer, and even a basic version of the
compiler is fairly expensive. The full version is very expensive indeed. Java
development systems are available from a wide variety of suppliers10 at a wide variety
of prices, depending on your needs.
Visual Basic only runs on windows platforms11, whereas Java will run almost
anywhere.
C++ vs Java
The Java syntax is based heavily on the C++ syntax. They are definitely not the same
language however – they both have a very different feel.
As mentioned at the start of the course, many of the dangerous features of C++ have
been removed – the example we worked through (Page 28) could not happen in Java.
C++ was never tightly controlled; it evolved in many different directions with many
people adding features in what seemed like an ad-hoc fashion. It finally became an
ISO standard in the late 1990’s, but it is still a very painful exercise to move from one
compiler to another.
We will look at the performance of the two languages later, but C++ is definitely a
much faster performer than Java; things are improving but not many people would
seriously consider building a real-time 3d graphics game using Java.
Perhaps the most important comparison is the relative productivity of Java and C++
programmers. The evidence from the field is that Java programmers are much more
productive than C++ programmers. Less bugs emerge during the development
process, and because Java has cut out many of the dangerous and abused features of
C++, the programmers can spend more time concentrating on the problem at hand,
rather than some obscure syntax problems.
C# vs Java
C# is relatively new, and Ariadne have little experience of C# to date, so it is difficult
for us to provide an objective comparison of the two. From a programming view, the
two are very difficult to separate. C# has taken a few technical points in Java and
improved on them, but that really would be the minimum we could expect after Java
has been in the field for seven years.
10
Although Java is still stubbornly owned by Sun Microsystems
11
The new .NET Framework may change this
As a rough comparison, Java has been in the field for much longer than C#, but that
situation will soon change. We shall watch the battle with a non-committal interest…
Perhaps more important than the differences between Java and C# is where C# fits in
with the new Microsoft .NET framework…
Microsoft .NET
.NET is promising to be one of the biggest revolutions in the industry ever. .NET is
essentially the pulling together of many of Microsoft’s technologies such as COM,
and the languages that Microsoft have been nurturing for so long (like VB and ASP).
We’ll look at the “server side” part of .NET in the second part of the course. From the
programming side, the most astonishing feature of .NET is that it is language
independent. Programmers essentially have the chance to work in whichever
language is suitable for them. A GUI developer would probably use VB; a
programmer writing complex logic may use C#. All the languages plug into the
framework and work together transparently - the C# coder can call the VB code
without even knowing they are working with VB code!
Summary
In this session, we compared Java to three other major languages
• C++ has been popular for many years, but it is showing its age and despite its
power, it is difficult and dangerous to use. It isn’t really owned by anyone in
particular but has extensive tool support
• C# looks and feels like Java; users on the .NET platform will use C# instead of
Java. It is owned by a major vendor; they appear to making the language free and
open to use
Chapter 4
Java Performance
Java Performance
The performance of Java (or perhaps, the lack of it) is perceived to be one of Java’s
greatest weaknesses. Here are two quotes we have dredged from the Java web site:
At run time, the Java Virtual Machine (JVM) reads in these bytecodes one by one, and
as they are read in, they are converted to machine code as and when required.
But how slow is slow? Clearly, this is subjective and depends on your requirements
and the domain you are working in….
Slow Java
The first releases of Java were indeed incredibly slow. Applets in particular ran very
sluggishly even on the fastest machines (again, this didn’t help Java’s reputation).
However, with each release of Java, the performance has become faster and faster.
There are two technologies working behind the scenes to help here. A Just In Time
Compiler is part of the virtual machine; it basically caches the machine code it
generates, removing the need for it to constantly compile the same code again and
again. This means that the first pass through your program may be slow, but future
passes speed up.
Hotspot VM’s are special Virtual Machines that contain performance evaluation
code. Where the VM detects bottlenecks in the code (ie Hotspots), the VM
automatically optimizes the code around the bottleneck.
Both of these technologies are completely transparent to you – they are just there.
Both technologies go from strength to strength, and Java’s performance improves at
each release.
We are going to first of all run the Java version, using the Virtual Machine provided
in release 1, back in 1996.
Then, we will run the program using C++ (and we expect a much faster performance).
Finally, we will run the program using the latest version of Java.
The program will, at the end of the run, report how long the records took to create in
memory.
Demo
Your results:
Language Time
Java 1.0
C++
Latest Java
Benchmark Summary
The Benchmark seems to suggest that up-to-date Java can compete in the same area of
performance as C++. However, this is only one simple benchmark and should not be
taken as cast iron proof.
Certainly, on the computational side, Java is now running fairly quickly thanks to Just
In Time and Hotspot VM’s. Having said that, the Java GUI is still a slow performer
(just think of all the drawing work it has to do!!), and can give the feeling of a less
responsive application.
Another performance issue is that Garbage Collection (see page 23) can and will kick
in at unpredictable intervals; sometimes this will pause program execution for a
perceptible amount of time.
A final and important point is that Java is very memory hungry; even 64Mb of Ram is
not suitable for a non-trivial application.
Treat these compilers with caution and ensure a full evaluation is carried out before
any commitment is made to licenses. Our evaluations have proved rather frustrating
when compiling non-trivial applications.
Summary
• The Java language has a reputation for being slow
• This reputation is based on its early incarnations, and was necessary due to the
platform independence
• Java is rapidly speeding up, thanks to “Just in Time” compilers and “Hotspot
VM’s”
• However, C++ will still outstrip it and there are plenty of outstanding issues
Chapter 5
Introducing J2EE
In this chapter, we introduce the Java 2 Enterprise Edition (J2EE), and describe its
main features. In the following chapters, we will go in to some deeper detail on the
main areas of J2EE.
What is J2EE?
As we described earlier, the Java language was originally conceived as a language for
building small programs embedded in electrical devices; its popularity was thanks to
this idea being twisted into using Java as a programming language for running small
applications (applets) in Web browsers.
Java has certainly moved on dramatically since then. Now, Java is being used to build
large enterprise systems – however, the Java language alone is not enough to meet the
requirements of an Enterprise system. A platform is required to provide some of the
services we need in such a system, such as12:
• The ability to store data in a commercial database
• The ability to distribute our application across more than one computer
• The support for transactions, to prevent data from becoming corrupted
• Multithreading, to allow concurrent access to our services
• Connection Pooling, to prevent our database performance from degrading
• Scalability – it is all very well our application working like a dream when we test
it in the factory, what happens when hundreds of people try to use it, all at the
same time?
An enterprise application cannot be located on a single PC – therefore we need to
employ some kind of architecture – a framework which lays down the guidelines for
where each component of our system is to be located. Very early systems were
monolithic – very thin clients (dumb terminals) would connect to a large database
running on a server – the so-called Two-Tier (or Client-Server) Model:
Two-Tier Architecture
The classic two-tier (or client-server) architecture was a move away, during the 80’s
and 90’s, from monolithic mainframe applications using dumb clients.
12
All of these topics, and more, will be explained and covered in more detail shortly
In a two-tier architecture, presentation logic (ie the code that produces displays for the
user and gathers input) is present on the client side of the application. In addition, the
bulk of the business logic is also present on the client.
The data is stored on a server, and the client would typically communicate with the
database using a language such as SQL. Sometimes, some business logic may be
present on the database server, perhaps in the form of stored procedures or daemon
(long-running) processes.
Presentation
logic
Business
Logic
The chief advantage of the client-server model is that is fairly simple to work with -
the database technology is well established and easy to understand, and the
programmers don’t have to worry about the complexities of more than one tier.
A classic example of the problems with the model is the problem such a system would
face if the graphical user interface needed to be changed in any way (for example,
changing the GUI from a Visual Basic application to a web based front end). As the
business logic is so closely tied to the presentation logic, it is impossible to change the
presentation code without impacting on the business code. It is probable that the
business logic would need to be completely re-implemented.
With the advent of the internet, it became possible to provide front ends to
applications through web browsers; however, given that a particular web browser
could be running on a myriad of platforms, embedding so much business logic on the
client side is not necessarily feasible or desirable.
Presentation Business
logic Logic
It is common to deploy the presentation tier on the client machines and the business
tier is deployed on a server. The business and presentation tiers are as loosely coupled
as possible; in other words the presentation tier simply dispatches requests off to the
business tier without knowing or caring how the job is being done. Similarly, the
business tier does it work and passes the results back the presentation tier without any
knowledge of how the data is going to be displayed.
The serious disadvantage with this model is the complexity involved in developing
such an application - doing so requires a knowledge of distributed computing (for
example, using RMI or Corba to call methods on objects on other tiers),
multithreading (to allow the business tier to handle requests from multiple clients at
the same time), security and so on.
Application Servers
Third party application servers can provide the framework that we need to develop a
multi-tier application, and provide the required services such as distribution, multi-
threading, security and persistence.
In the past, each server product was developed independently, and therefore each
provided different services, each service was implemented in a different way (and so
the programmer would have to jump through different hoops depending on the server
in use).
Clearly, this would mean a project would have to choose an Application Server and
stick with it - changing between application servers would be difficult, if not
impossible.
It is important to note that J2EE is not a product; you cannot download a software
product called “J2EE” (as you can with J2SE). J2EE is a specification for which there
are many different implementations.
The implementations are provided by third-party vendors (such as IBM and BEA).
These implementations must conform to the J2EE standard to be able to call
themselves “J2EE Compliant”.
Sun provide a free product called the reference implementation which conforms to
the J2EE standard - it is free to download and use, and is ideal for learning about
J2EE and also for testing or prototyping. It doesn’t do much more than the J2EE
requires, however, whereas third party commercial implementations are likely to be
much more suitable for live applications.
J2EE Components
The J2EE defines three types of component an application programmer can develop:
• Servlets
• JSP’s
We will look at each of these in very brief detail for now – we’ll explore each of them
as we progress through the course.
Java Servlets
Servlets provide a method of writing server side Java programs. A common use for
servlets is the dynamic generation of web pages. For example, it would be possible to
build an interactive guestbook on a web site using a Java servlet.
Servlets are a replacement for the traditional “CGI” (Common Gateway Interface)
method of providing interactive webpages. The use of CGI is very popular and
widespread, although CGI’s can suffer from performance and scalability problems,
and are usually written using Perl – a popular niche language but certainly not to
everyone’s taste!
A JSP looks very much like standard HTML, and so should feel familiar and
comfortable to existing HTML programmers. The difference is that JSP allows
fragments of Java code to be embedded into the web page.
An EJB is a Java class that possesses several special features. Enterprise Java Beans
are:
• Distributed
• Transaction-aware
• Multi-threaded
• Persistent
Many of the features of an EJB are provided “for free” by the application server,
relieving the programmer of the tedious job of implementing these details. Therefore,
the programmer can concentrate on the important work of coding the business logic.
Client (eg - PC
or browser) Web Container EJB Container Database Server
Presentation Web
EJB
logic Application
In order to accommodate the needs of building web based enterprise applications, the
J2EE spec is based around 4 tiers rather than 3, although the theory and reasoning
behind the separation remains the same.
An EJB Container will also be provided as part of the application server - this is a
server that can provide our Enterprise Java Beans with all of the services that we
need.
Note that a J2EE based application does not need to be a web application - it supports
any type of client - in an application not based on the web, the client tier talks directly
to the EJB Container, and the Web Container is not used.
Intranet
Data Entry EJB Server
Forms/
Queries
Webserver
Running control servlets Orders
HTML Forms EJB Oracle
Stock
EJB
Radio
Radio
Data
Radio
Data
Terminal (RDT)
Radio Customer
TerminalData
(RDT)
Radio
Data EJB
Terminal (RDT)
TerminalData
(RDT)
Terminal (RDT)
EJB’s - control and model
Running standard Java Applications
The Radio Data Terminals are running standard Java Applications (or possibly even
J2ME applications – see page 10). The HTML forms are standard web pages.
We would have some J2EE servlets running on the webserver – these provide any
control logic that the web forms need. More on this in the next chapter.
The EJB Server holds the bulk of our business logic. For example, the functionality
to credit check all customers held on the system will be held in a component, written
in Java that has been deployed on this server. These components are the Enterprise
Java Beans. These EJB’s will contain data about the customers – and these will be
stored on (in this case) an Oracle database. More on this later.
Summary
• The J2EE Specification provides a standard for Application Server vendors
• The components defined by the specification are written by the Java programmer:
Chapter 6
Servlets and JSP
To build elegant, maintainable and scalable J2EE systems, it is critical that your
engineers follow certain rules when writing servlets and JSP’s – we will discuss these
rules at the end of the session.
The client (web browser) requests a page from the server. The server responds by
sending a stream of data back to the client.
1 : get
2 : webpage
Let’s say we want an interactive message board, to which users can post information.
We will need to store these messages on a database on the server, and when the users
want to view the information, we will need a program to query the database and build
the webpage to show the up-to-the minute collection of messages. The scheme
described in Figure 19 is not sufficient to achieve this.
Solution: CGI
One solution was a technology called CGI, or Common Gateway Interface. This
gave programmers the means to write server side programs that could intercept
requests from clients, and to generate the response page dynamically.
CGI is a very, very popular technology and although it is a bit old now, you will still
see many web pages using CGI (look at the address of many web sites – if you see
“cgi” or “cgi-bin” appearing somewhere in the address, you are using CGI).
There were some problems associated with the approach. First of all, although any
language could be used to implement CGI programs, a language called perl was
considered the best. Perl is an excellent language, but rather specialist and definitely a
niche language (text processing is one of its strengths).
CGI is all very well if you are performing relatively simple tasks like building
message boards, but moving into the realms of serious software engineering (e-
commerce sites, etc) is pushing things a bit far. CGI is also renowned as being a poor
performer (due to threading problems), and there are some serious security loopholes
with CGI.
Their operation is simple, and very similar to the CGI scheme described above. The
servlet sits on the server, doing nothing, until a request from a web page comes in.
The request is intercepted by the servlet, the serlvet then does some work (anything
the programmer wants to do), and then the servlet sends the results back, in the form
of a web page.
• We can use Java – a more serious and deep language than perl
An Example Servlet
We’ll now demo a simple servlet. The code follows below - don’t worry about all of
the details, but you should notice that the program is outputting HTML, and one of
the outputs is the current date and time. So this is a dynamic webpage (albeit a very
dull one), rather than a prewritten static webpage.
This creates a maintenance nightmare. What happens if you want the look and feel of
your web page to change? You have to trawl through reams of Java code looking for
those out.println() statements. Also, it is necessary for your HTML coders to have a
reasonable working knowledge of Java to even know how to make the changes.
This very unpleasant situation has a possible solution, called JSP – Java Server
Programming…
Consider the following JSP file, a web page that outputs the date and time:
<html>
<html>
<head>
<head>
<title>What
<title>What Time
Time Is
Is It?</title>
It?</title>
</head>
</head>
<body>
<body>
<h3>You
<h3>You requested
requested this
this page
page on
on ::
<%=
<%=
new
new java.util.Date()
java.util.Date()
%>
%>
</h3>
</h3>
</body>
</body>
</html>
</html>
Here, most of the JSP is standard HTML, but notice the block of code in bold type,
between the <% and %> markers. This is standard Java code.
JSP Architecture
How does this actually work behind the scenes? It’s all a bit of a trick really. We
deploy the JSP onto the server, where it is automatically converted into a servlet!
HTML Page
6 6 6
JSP Java
Servlet
Eng ine
1 2 5
Source Generated 4
Java Servlet Clas sfile
JSP File Java Servlet Compiler
Step 1) the client requests a JSP page (in other words, the user types in a URL
something like http://www.myhost.com/booklist.jsp)
Step 2) the server catches the request for a JSP page. The server finds the JSP file, and
then passes it on to a program, running on the server, called the “JSP Engine”
Step 3) The JSP reads the JSP file, and from this basic information, it generates a Java
Servlet (automatically!)
Step 4) The generated Java Servlet is compiled using a standard Java compiler
(remember - all this is happening while the user is waiting for their page!)
Step 5) The new Java servlet is now executed by the JSP engine. The servlet, as in the
previous chapter, generates HTML “on the fly”
Step 6) We now have a HTML page - the page is passed back to the web server and
then finally it is returned to the client.
Note that the compilation of the servlet does indeed take some time and you will
notice that the first request of a JSP page is SLOW! The JSP then stores the resulting
class file, however, because subsequent accesses will be much faster.13
<html>
<html>
<head>
<head>
<title>First
<title>First 10
10 Squares</title>
Squares</title>
</head>
</head>
<body>
<body>
<h1>The
<h1>The First
First 10
10 Squares:</h1>
Squares:</h1>
<hr>
<hr>
<%
<% for
for (int
(int i=1;
i=1; i<=10;
i<=10; i++)
i++)
{{
out.println
out.println (i*i);
(i*i);
}}
%>
%>
<hr>
<hr>
</body>
</body>
</html>
</html>
13
Some Application Servers compile the JSP when the JSP is deployed rather than first accessed. This
obviously increases performance, but it isn’t mandated and the reference implementation does not do
this.
If we begin to write JSP pages with Java logic scattered all over them, we have the
same maintenance nightmare as before – if we need to make any changes to the way
the application works, we are going to have to laboriously hunt through masses of
HTML code! Conversely, the HTML is going to be scattered amongst lots of very
awkward looking Java fragments.
Solution: Servlets!
We now have the situation where:
• Servlets are a good idea, they are good at doing “brain-work” (application logic),
but they are poor at the presentation of the results – those nasty out.println()’s
• JSP’s are a good idea, they are excellent at doing the presentation but degenerate
into a mess if they try to do too much brainwork
Well, the answer is to get the two to work together as a team! Let the servlet handle
the Java logic, then get it to send its results onto a JSP – which can then do the job of
displaying the results.
It is imperative, to achieve success with J2EE on your project, to enforce this model.
Standard
Project
The The
“View” The “Model”
“Controller”
HTML
or JSP servlet Other Java
Java in JSP’s
Are there rules about what Java should be allowed in a JSP page? The general answer
is “as little as possible”, and the MVC/Model-2 principle must be followed.
• Simple loops – eg running through multiple products, and displaying each one in
turn
Custom Tags
A Custom Tag is a new enhancement to JSP that allows the JSP coder to perform
complex operations without the need for Java code. A tag is essentially a macro used
by the JSP programmer – even though the tag is quite simple, it turns into complex
Java “behind the scenes”.14
The concept of custom tags has been, until recently, in its infancy. No standard set of
tags were available, and it was really up to projects to write their own “Tag Libraries”.
This is quite a difficult process to do, and of course this means the code your project
writes is non-standard. An alternative was to download third-party tag libraries, but
these libraries were patchy and sometimes quite complex.
At last (and only just, at the time of writing), a standard tag library has been specified.
It is called the “Java Standard Tag Library” or JSTL, and this library will become part
of the J2EE specification.
Here’s a quick example of where tags might be useful. Again, you don’t need to
understand the Java, as long as you get a flavour of what is going on:
JSP Example
This JSP page is responsible for displaying all of the items in stock in a warehouse.
We have some standard HTML in here as usual, but the bold code is the Java code
that runs through each item of stock and extracts the details of the stock:
14
Ie – when the JSP is converted to a servlet
<i>The
<i>The following
following items
items are
are in
in stock</i>
stock</i>
<pre>
<pre>
<%
<%
Collection
Collection results
results ==
(Collection)request.getAttribute("stockListResult");
(Collection)request.getAttribute("stockListResult");
Iterator
Iterator it
it == results.iterator();
results.iterator();
while (it.hasNext())
while (it.hasNext())
{{
String
String next
next == (String)it.next();
(String)it.next();
%>
%>
Item
Item :: <%=
<%= next
next %>
%>
<%
<% }} %>
%>
This JSP conforms to the rules we have discussed. It doesn’t do any brain work; it is
given a set of data and the Java code simply extracts each result, and the JSP displays
the name of the stock on the web page.
Even though we have followed the rules, it is still a bit messy, and very heavy on the
Java. Here, a Tag from the JSTL will help:
<i>The
<i>The following
following items
items are
are in
in stock</i>
stock</i>
<pre>
<pre>
<c:forEach
<c:forEach var=”item"
var=”item" items="$results">
items="$results">
Item
Item :: <c:out
<c:out value="${item}"/><br>
value="${item}"/><br>
</c:forEach>
</c:forEach>
Summary
• The J2EE specifies two type of web component that can be written in Java:
Servlets
15
Reference [8] is a good guide to the JSTL
JSP’s
• JSP’s enable the creation of dynamic web pages as well, but rely much less on
explicit Java coding
• Custom Tags and the JSTL provide another way of hiding the Java in a JSP Page
Chapter 7
Enterprise Java Beans (EJB’s)
In this session, we will look at the concept of Enterprise Java Beans, or EJB’s. We’ll
look at the different types of EJB, and find out about the features that EJB’s offer.
Java Beans
Sun invented the concept of a Java Bean some years ago, in an attempt to extend
Java’s reach into the area of Rapid Application Development.
We saw in “Java vs Other Languages” session (Page 26) that Visual Basic allows
developers to rapidly build applications by dragging and dropping prebuilt
components on to the screen, and then by customising the components by changing
some properties.
Sun’s idea was that a Java Bean would become the equivalent of the Visual Basic
Components. A Java Bean is a standard Java Class, but one that is simple and easy for
programmers to reuse themselves. For example, the “Button” in Swing (see Page 16)
is a Java Bean. The programmer can change the colour of the button, the behaviour of
the button and so on, but most of the work has already been done for them.
Java Beans are often graphical, but not necessarily. As long as the Java Class
conforms to a collection of “Design Patterns”, simple guidelines as to how the class is
written, then it qualifies as a Java Bean. The key aim is that regardless of what the
Bean is, it has a collection of properties that can be accessed and customised by the
programmer.
Figure 31 - A JavaBean (in this case, the Button from the Swing classes). The
programmer has customised the bean slightly, but most of the work was already
done for them
From a theoretical point of view, Java Beans are easy to design and build – but in
reality, there are some catches that make good Beans very difficult to build well.
Therefore, commercial Java Beans can be quite expensive to buy.
However, EJB’s live on servers rather than inside standard desktop applications. Since
they are server based, they are never graphical, unlike standard Java Beans, which
often are.
The most striking feature of EJB’s is that they provide your programmers with a
whole raft of functionality that is essential when building large scale systems. All of
this is done for them, so they can concentrate on the job in hand.
EJB’s Are:
• Persistent
• Transaction Aware
• Distributed
• Multithreaded
We’ll look at each of these concepts in turn. All of these features are provided “for
free” – the programmer of the EJB doesn’t need to manually implement any of it. The
trick is that your programmer’s EJB’s are “wrapped” in a piece of software called the
EJB Container, provided by the Application Server.
can be tailored to your own needs if required, but it is done in the tool rather than
polluting the Java code).
Our general advice is aim for CMP if at all possible – it is much more elegant and is
one of the strongest features of EJB’s. We’ll return to this topic in a short while.
In this example, we have set a Java method called “buy” to be a single transaction. If
anything goes wrong part way through the process, any changes made as part of that
method will be automatically rolled back.
Credit Check
Customer
no
ok?
yes
Clearly, if the process crashed (for whatever reason) after the order had been added to
the list, but before the invoice was added to the queue, we would have a fairly serious
business problem. By running the procedure as an EJB, we can make the entire
process a transaction.
If more fine grained control is required (let’s say we wanted to start the transaction
after the credit check, and end the transaction once the invoice is raised), then this can
be done by the programmer using a fairly simple “start transaction” and “end
transaction” process.
However, the programmer using the EJB (the client programmer) doesn’t need to
know anything about where the EJB is physically located. They follow a fairly simple
procedure of “looking up” the EJB to get a handle on the bean; and then they call its
methods exactly as they would do with a regular Java class.
All of the nasty network mechanics happens behind the scenes in complete
transparency (by the way, the technique used is called RMI or Remote Method
Invocation – any programmer who has used RMI by hand will testify, it is a fairly
unpleasant technique!)
The application server will automatically manage threads so that the two tasks can
happen in parallel – and once again, no programmer intervention is required to make
this happen.
In addition, the application server will also intelligently pool resources. For example,
a thousand clients might all be trying to access the same EJB at the same time; the
application server will be able to share a limited number of EJB’s amongst those
thousand clients, thus preserving resources and preventing excessive server load –
again, all this happens without the programmer needed to code anything special to
make this happen.
Types of EJB
Although until now we have considered an EJB to be a single concept, in fact there
are actually three different types of Enterprise Java Bean available. The three types
are:
• A Session EJB
• An Entity EJB
Session beans are in very common use – these are usually beans that are primarily
written to do something. For example, we might have a session bean responsible for
credit checking customers, or for placing orders (as on Page 55).
Session Beans are not persistent – any data they hold will be lost when the system is
restarted.
Entity Beans are EJB’s that provide the persistence features we discussed earlier.
They are usually used to represent the real world “objects” that exist in the system.
Examples of Entity EJB’s would be Customer, StockRecord and PurchaseOrder.
You could think of an Entity Bean as being “data storage” beans, but they are Java
classes, and so can do things just as with a session bean.
Message Driven Beans are Java Classes that are capable of responding to “Messages”
sent to them. The benefit of an MDB is that they can work asynchronously – in other
words the client asks the bean to do something, and the client can go off and carry on
with some other task, while the MDB is responding to the message at the same time.
This is a powerful facility, but we won’t explore it in any depth on this course.
Entity Beans
The concept and implementation of Entity Beans is very controversial (at the time of
writing; things change quickly in J2EE!). Many J2EE applications have studiously
avoided implementing entity beans, and have been happy to settle with Servlets, JSP
and Session Beans.
This will work perfectly well; an entity bean can be replaced by a standard class (you
will see these referred to as “Plain Old Java Classes” – POJO’s). These plain Java
classes use JDBC calls to manually manipulate the underlying database.
Remember, however, that this manual use of JDBC is a pollution of your Java code, it
is less maintainable and perhaps less understandable. But on the other hand, many
people find Entity Beans difficult to understand and use anyway.
Much of the confusion about Entity Beans has been attributed to the original
specification of them – it was allegedly poorly written and difficult to understand.
The choice is entirely down to your project and its senior designers. However, be
aware that a new version of the Entity Bean spec has now been released – it is called
EJB 2.0, and it fixes many of the original problems with Entity Beans.
As long as certain design principles are maintained (more on this shortly), Entity
Beans are now viable for serious developments, and they certainly are a powerful tool.
We’ll look at a quick example of a simple design pattern – our aim is not to teach
design patterns, as that is beyond the scope of this course – but we do want to give the
flavour of design patterns, and establish that understanding them is critical to building
good systems.
Our advice is to ensure that your designers and programmers are familiar with at least
some of the patterns, and that your project embraces the teachings of the patterns.
If you are planning to buy a J2EE Design Patterns book, ensure that the book covers
EJB 2.0, as the new version of Entity Beans has made some of the design patterns
redundant. An excellent design patterns book is available for free download – see
reference [4].
Customer
getCustomerDetails EJB
Web
Page getPODetails
(JSP)
Purchase
Order EJB
Application
Client
Server
Figure 33 - Our first design attempt
This will work. Our client application (in this case it is a web page, but it could have
been a standard Java application) makes calls to the Enterprise Java Beans on the
server. Remember, this is possible and easy because EJB’s are distributed and the
client programmer can easily locate and call the beans.
Our design has the client calling the Customer EJB first to get the customer data, and
then it follows with a call to the Purchase Order EJB. The information is then
displayed on the web page.
Design Problem
Assume that this application works. The J2EE Design Patterns tell us that it isn’t a
very good design however – it will perform badly, especially as the application scales
up.
The reason is that the calls across to the EJB’s are slow. They are travelling across a
network, or possibly even the internet. Essentially, having two separate calls is
wasteful. Applying a Design Pattern will help here…
Design Solution
The solution is called a Session Façade – all design patterns have recognizable
names. The Session Façade guides us to remove the multiple calls across the network
and replace with one single call.
We will require an extra EJB to make this work, however – usually we will use a
Session Bean16. We make a single call to the session bean, and then the session bean
can talk to the EJB’s on the server.
Customer
getCustomerDetails EJB
Web listCustomers
ListCustomers
Page
Session EJB
(JSP)
Purchase
getPODetails Order EJB
Application
Client
Server
Figure 34 - The new design, using a Session Façade
This has cut down the network “chattiness” and will certainly have a significant effect
on performance, especially when we scale the system up, or if the List Customers
process becomes more complex with more calls.
This is just one design pattern (it happens to be the most common and one of the most
important), but as we have mentioned, there are plenty more and investing time and
effort into learning them will pay off in spades for your project.
EJB Summary
• Enterprise Java Beans are similar to standard Java Classes
• There are three different types of EJB – Session, Entity and Message-Driven
• Entity Beans are the persistent type of Bean and have been quite slow to gain
acceptance
16
This makes sense – recall we said that Session Beans usually do something rather than holding onto
data
Chapter 8
The Javadoc Tool
Before we finish, we are going to take the opportunity to introduce the (sometimes
neglected) javadoc tool. This remarkable tool, provided for free as part of the Java
toolset, automatically generates technical documentation for your project’s code.
The documentation follows exactly the same format as the Java Help that we saw in
“Java Help” (page 12) – and the files you generate integrates closely with the standard
Java help.
This is a tremendous benefit to your programmers and designers, and is usually worth
the added development effort involved.
/**
/** This
This class
class holds
holds information
information about
about an
an
** Employee in the company
Employee in the company
*/*/
public
public class
class Employee
Employee
{{
protected
protected int
int salary;
salary;
private
private String
String employeeCode;
employeeCode;
private
private Calendar
Calendar dateOfJoining;
dateOfJoining;
……
}}
Figure 35 shows an Employee class with a javadoc comment (the rest of class also
needs to be commented – we’ve omitted this for space). The javadoc is distinctive
because of the “/**” symbol.
These files can now be browsed by your project – they can also be picked up by your
Java development IDE if you are using one (eg – pressing F1 on the Employee class
will bring up the Employee help file!).
Javadoc Demonstration
We will now demonstrate the generation of javadoc help for a non-trivial project
(more than 100 classes).
Summary
• The Javadoc is an inspired addition to the Java toolset
• Projects that use it report higher productivity and a more maintainable product
• Clearly, to get value from the tool, an investment of time has to be made with
putting the correct comments in the code
Chapter 9
Course Summary
We have explored the principle features of Java, from the “standard features” (GUI’s,
Threading, JDBC, etc) through to the more recent and advanced “enterprise features”
provided by J2EE.
It is important to be proficient in standard Java before diving into the enterprise side
of Java – but once programmers reach a reasonable standard of ability in Java, many
people report it is a well designed and “Engineer Friendly” language. Certainly,
reports from the field suggest that Java projects tend to turn out code faster and more
reliably than those working on C++ and similar languages.
As always, the IT world is changing quickly; who knows how long Java will continue
to hold such an enviable position? C# and .NET are certainly going to be major
competitors in the near future…
Java Problems
After dozens of pages extolling Java’s virtues, what are the problems with Java?
One problem (which could be considered a benefit by many) is that Java is still a
cutting edge language and is riding on a wave of technologies. Check the
java.sun.com website, and you will find a raft of acronyms for lots of very fancy ideas
(and often it is impossible to tell what these ideas actually are – often the technical
enthusiasm gets in the way of human understandable descriptions of the ideas!) Many
of these technologies get trumpeted as “the next big thing”; most of them you will
never hear of again. It can all be a bit overwhelming, especially when all you want is
to get your product delivered on time and on budget.
J2EE is an incredibly difficult topic to get to grips with. Most of the books currently
available on the topic were written by the people behind the development of J2EE
itself – and in many cases these books prove to be too complex and involved to gain
understanding from. At last, “Teach Yourself” books are beginning to emerge, so
perhaps at last J2EE will be easier to grasp for most programmers. (see reference [5]
and [6]). No matter how complex J2EE is, a grasp of the “Design Patterns” (see page
58) is essential to the success of any J2EE development.
Finally, as we have touched on in many areas of this book, .NET is a serious new
technology and is likely to change many things. A common view is that both .NET
and J2EE will continue to carve out their own niches, and a kind of “stalemate” will
eventually occur between the two. Who would dare to predict the outcome?
Bibliography
[1] : Knowles, Richard; Dundas, Kenny; Golledge John. 2001 UML Applied : Object
Oriented Analysis and Design Ariadne Training
A cracking guide to the UML and Object Orientation, but we would say that. Available for download at
www.ariadnetraining.co.uk.
[4] : Marinescu, Floyd. EJB Design Patterns John Wiley & Sons
This is superb and readable book; an excellent treatment of this very difficult topic. A downloadable
version is available at www.theserverside.com - but we recommend you buy it!
[5] : Deitel and Deitel. Advanced Java 2 Platform : How to Program Prentice Hall
A very comprehensive and programmer friendly guide to advanced Java (such as Java 2D and 3D), but
more significantly covers J2EE in astonishing detail, and avoiding the complex and unnecessary depth
the appears in most J2EE books. They describe how to build full J2EE applications, and even cover
J2ME.
[7] : Collins, Tony. 1998 Crash : Learning from the World’s Worst Computer
Disasters Simon&Schuster
An entertaining collection of case studies exploring why so many software development projects fail;
referenced on this course to prove that C++ programs can occasionally crash