67
©2002 Ariadne Training Limited Java and J2EE An Introduction Course Companion

Java J2EE Intro Course Book v2

Embed Size (px)

DESCRIPTION

An introduction to JAVA and J2EE

Citation preview

©2002 Ariadne Training Limited

Java and J2EE An Introduction

Course Companion

2 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Contents

CONTENTS 2

The Purpose of this Book 5

THE HISTORY OF JAVA 6

Background to Java 6 Java Applets 7 Java Applications 8 Server Side Java 9 Summary 9

JAVA SOFTWARE DEVELOPMENT 10

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

JAVA VS OTHER LANGUAGES 26

Language 1: Visual Basic 26 An Example VB Program 27 Language 2: C / C++ 27 Example C++ Program 28

3 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

SERVLETS AND JSP 42

Servlets and JSP 42 The Static Web 42 Making the Web Dynamic 43 Solution: CGI 43 The Servlet Solution 44 An Example Servlet 44 A Serious Problem Emerges 44 Java Server Programming (JSP) 45 JSP Architecture 46 Another Dynamic Webpage 47 Another Problem Emerges! 47 Solution: Servlets! 48 The MVC Architecture 49 Java in JSP’s 49 Custom Tags 50 JSP Example 50

4 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Using a Custom Tag 51 Summary 51

ENTERPRISE JAVA BEANS (EJB’S) 53

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

THE JAVADOC TOOL 62

How the Tool Works 62 Running the Tool 63 Javadoc Demonstration 63 Summary 63

COURSE SUMMARY 65

Java Problems 65

BIBLIOGRAPHY 67

5 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

To submit comments or questions, please email [email protected], or see our website at www.ariadnetraining.co.uk.

Proj

ect

Stan

dard

If you’re a project manager on a new Java project, you may find some of our suggestions to be useful as possible project standards. We’ll break out these 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.

6 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

7 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Figure 1 - A Java calendar Applet

Applets have many interesting features and advantages:

8 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

• 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!

• Secondly, Applets are inherently limited in their functionality4. We said above that Applets are not capable of deleting all of the files on a user’s hard disk – in fact Applets are not capable of even accessing a user’s hard disk! Nor can an Applet contact any web site other than the one it was downloaded from. These are serious restrictions that essentially prevent many interesting Applets from even being written.

• 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

9 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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 More recently, Java has also become recognised as a server-side language too. For example, the concept of a servlet enabled web pages to contact small Java applications running quietly on a server; the servlet could perhaps work with a database and return results back to the user viewing the webpage. We’ll look in more detail at servlets later.

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

• Applets have largely failed to deliver their initial promise

• However, Java is a very well designed language and is now being exploited to build full blown applications

Java reached maturity at version 1.2 (1998)

• Java is also being exploited as a Server Side language

We’ll look at this in the second half of the course

10 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

The Java Development Kit The Java language is actually fairly simple; as we have mentioned, the syntax is derived from C++, but with extreme simplifications.

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.

11 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Evolution of the SDK The first release of Java, 1.0 emerged in January 1996 (beta versions had been available before this date). Whilst interesting, the language was in its fledgling state and suffered from many flaws. Version 1.1 (Feb 1997) improved things considerably, and then with the release of 1.2 in December 1998, Java reached what can be considered as the baseline of “maturity”.

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.

12 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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).

Figure 2 - Example Java help file. An experienced Java programmer working with files for the first time would be able to read this help file and quickly get to

grips with how the class works

13 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

The Key Java Features We’ll now examine each of the major features of Java in turn and explain how they benefit a software development project:

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.

To make a program run on a different platform, the program would have to be converted manually by a programmer or team of programmers – a process known as porting. This is a time consuming and difficult job to perform.

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.

The Java Virtual Machine Before Java, most programs would be run through a tool called a compiler. The job of the compiler is to convert the program into platform dependent machine code. Once the code is compiled, it would only run on the machine it had been compiled for.

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.

14 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

CompilerJavaSource Bytecodes JVM

NativeMachine

Code

Design time

Runtime

CompilerJavaSource Bytecodes JVM

NativeMachine

Code

Design time

Runtime

Figure 3 - How the JVM achieves platform independence

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.

Graphical User Interfaces Java features the capabilities to build Graphical User Interfaces (GUI’s) as part of the class libraries. There is no need to use an external library or tool as with other languages.

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…

15 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Figure 4 - A Macintosh running Max OS X (The Aqua Look and Feel)

Figure 5 - A PC Running Windows 98

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.

16 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Figure 6 - An AWT User Interface

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.

Swing to the Rescue Just before the release of Java 1.2, a new approach to building GUI’s in Java was devised, called Swing. Using the new approach, Java simply asks that the operating system is able to:

• Present a Window

• Draw on a blank canvas (using simple pixels)

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

17 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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:

Figure 7 - A Swing GUI

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

18 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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:

Figure 8 - 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.

19 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

The provision of the facility to allow Multi-Tasking is woefully absent in many major modern languages. In particular, C++, a very common and popular language, has no “in built” support for doing more than one thing at the same time. Programmers in C++ have to rely on messy system calls (destroying any chance of portability), or they have to purchase non-standard third party libraries.

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.

Multi-threading is required for Enterprise systems of course (the previous example, where we have two customers trying to order at the same time is a case in point). We will see later, however, that the multi-threading is provided behind the scenes if we are using J2EE, so thankfully your programmers are relieved of this difficult and time consuming task.

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:

20 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

public class NumbersThread implements Runnable{public NumbersThread(){

Thread thread = new Thread(this);thread.start();

}

public void run(){

for (int i=1; i<=500; i++){

System.out.println (i);}

}}

Figure 9 - Java Multithread Program

Running the Multiple Threads If we now ask Java to run two versions of the code in Figure 9, we will have two parts of the program outputting the numbers from 1 to 500 at the same time.

The Output Here is the output from a run of the program where two versions of the code are running concurrently:

21 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

…1181191201211221231241251126212731284129513061317132…

Figure 10 - Output from the Program

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.

22 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Exception Handling Example8 Here, the programmer is trying to connect to a database using the following line of code:

DatabaseDriver.connectToDatabase ("employees");

Figure 11 - Connecting to the Employees database

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}

Figure 12 - This will now work

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.

Proj

ect S

tand

ard

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.

23 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Java Garbage Collection A serious problem in some languages is the need for a programmer to constantly “clear up” after themselves. For example, imagine a programmer has created an “object” to hold the contents of a user’s shopping cart. When the customer logs off, the cart and its contents (in memory) are no longer required. In many languages, the programmer must remember to explicitly delete the object.

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

24 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

No extra libraries, plug ins or third party tools are required

• The language is very well designed

It is fully object oriented

9 A standard for connecting to relational databases; most databases will support it

25 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

It is platform independent

It features GUI capabilities, built in

Multithreading in an integral feature

Elegant error handling is also built in

“Garbage Collection” is automatic and requires no programmer intervention

Java is database aware

26 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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 1: Visual Basic It is claimed (or was once claimed) that Visual Basic is used by over 50% of the world’s programmers. A quick web search has failed to confirm this claim (we can find a few references to the claim scattered around the web, but we can’t find the source of the claim). It was a fairly bold claim, distorted by the fact that Microsoft Office uses Visual Basic as its Macro creation language – so if you have ever used a macro in MS Office, you have technically “used” Visual Basic. Whatever – VB is a very popular language indeed.

It is a proprietary language, produced by Microsoft Corp. It’s goal is to enable the creation, rapidly, of graphical user interface intensive applications. Not surprisingly, the language is based on the old language BASIC (Beginners All Purpose Symbolic Instruction Code), a language that dates back decades and was originally designed for teaching purposes. VB’s heritage has lead many “serious” programmers to deride the

27 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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).

Figure 13 - Bjarne Stroustrup, the creator of C++

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.

28 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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:

Example C++ Program A nice, simple program. Just two lines of executable code. Don’t worry if you don’t know any C++ syntax; your lecturer will take you through it.

int main (void)

{

// a simple program that fills an array with squares…

int square_array[10];

int count;

for (count = 1; count <= 10; count++)

square_array[count] = count*count;

// now print the results…

for (count = 1; count <= 10; count++)

cout << square_array[count];

}

Figure 14 - A Simple C++ Program

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.

29 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

It is pitched at a level somewhere between VB and C++. It aims to be more powerful and general purpose than Visual Basic, but “safer” and easier than C++ (ie avoiding the kind of mess we saw on page 28).

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.

Now, let’s compare the three languages to Java.

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.

30 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

31 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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!

Coders working on a Java/J2EE project have no choice – it’s Java or nothing…

Summary In this session, we compared Java to three other major languages

• VB is best for developing “small”, “simple” GUI intensive applications. It is owned by a major vendor and for many years has been proprietary

• Java is best as a more general purpose, powerful but safe applications/server based language. It is owned by a major vendor but one who seems to be committed to a free and open use of the language

• 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

32 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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: • “86% of users expressed concern about the performance of Java based

applications” • “Java technology seemed to have a knack for turning a fast Pentium into a

plodding 386!”

Is the performance of Java Applications really a problem?

Why Should Java be Slow? Recall from “The Java Virtual Machine” (Page 13), Java is not converted into a native executable application. Instead, the Java code is compiled into a set of platform independent bytecodes, a kind of platform independent machine code.

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.

So, as a Java program is running, a translation process is constantly going on – and this is the reason your Java programs run slow.

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.

33 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Demo and Benchmarks We are now going to run a simple benchmark. This small application adds a million customer records into memory, each record containing a customer id, a name and a credit rating. We have implemented the program using C++ and Java, and while our C++ skills are not first rate, we have aimed for similar implementations of the two.

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

34 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Native Code Compilers Compilers exist that claim to be able to compile Java into true 100% native code, ie full executable programs. Obviously, this renders your programs non-portable - but for many projects this isn’t a problem.

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”

• Java can now cut it with the fastest languages

• However, C++ will still outstrip it and there are plenty of outstanding issues

35 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

36 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Database ServerDatabase ServerClient (eg - PC)

Presentationlogic

BusinessLogic

Client (eg - PC)

Presentationlogic

BusinessLogic

Figure 15 - The Two-Tier Model

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.

There are serious disadvantages to the two-tier architecture, however...

Two-Tier Architectures: Disadvantages The fundamental problem with this architecture is that the business logic and presentation logic are tied together, making for a system that is difficult to understand and maintain.

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.

37 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

The Three Tier Model The three tier model splits the presentation logic and the business logic into two separate tiers.

Client (eg - PC)

Presentationlogic

Client (eg - PC)

Presentationlogic

Business Server

BusinessLogic

Business Server

BusinessLogic

Database ServerDatabase Server

Figure 16 - The Three Tier Model

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.

To remove the burden on the programmers, an application framework (these days commonly referred to as an application server could be purchased from a third party to provide such services...

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.

38 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

However, in 1997 a group of application server vendors (including BEA, IBM, Oracle, Sybase and Sun themselves) began working together to define a standard for application servers, based on the Java language. The vision was to create a standardised set of services, and a standard API for accessing these services.

The J2EE Standard The J2EE Standard rigorously defines a set of services that application server must support, together with a standard API for accessing those services. The standard is closely tied to the Java language, so the method of writing code to access the Application Server’s services is clear.

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

• Enterprise Java Beans

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!

39 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Java Server Pages (JSP) Java Server Pages allow web designers to build interactive web pages without getting into the deep details of the Java language.

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.

Enterprise Java Beans (EJBs) Enterprise Java Beans are perhaps the most significant of the three types of component.

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.

The J2EE Architecture The J2EE Architecture is very similar to the three tier model, although it is extended a little further to accommodate web based applications:

Client (eg - PCor browser)

Presentationlogic

Client (eg - PCor browser)

Presentationlogic

Database ServerDatabase ServerWeb Container

WebApplication

Web Container

WebApplication

EJB Container

EJB

EJB Container

EJB

Figure 17 - The Full J2EE Architecture

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.

40 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

A J2EE Compliant Application Server will provide a Web Container, which is a server that allows servlets to be deployed. We’ll explore this in detail in the chapter on servlets.

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.

Concrete Example – A Warehouse Consider a warehouse running an automated stock/picking system. Orders are entered into the system using web based pages running on a small intranet. Moving around the warehouse are a collection of workers carrying Radio Data Terminals dishing out instructions on which orders to pick etc.

A possible J2EE implementation of this might look as follows:

RadioData

Terminal (RDT)RadioData

Terminal (RDT)RadioData

Terminal (RDT)RadioData

Terminal (RDT)RadioData

Terminal (RDT)

IntranetData Entry

Forms/Queries

WebserverRunning control servlets Orders

EJB

CustomerEJB

StockEJB

EJB Server

OrdersEJB

CustomerEJB

StockEJB

EJB Server

Oracle

Running standard Java Applications EJB’s - control and model

HTML Forms

Figure 18 - Warehouse J2EE Architecture

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

41 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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 specification enables the construction of applications built around a multi-tier architecture

• The components defined by the specification are written by the Java programmer:

Servlets (server side Java classes accessed by browsers)

JSP (HTML-like files with embedded Java)

Enterprise Java Beans - distributed, transaction-aware, persistent, multi-threaded Java components

42 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Chapter 6 Servlets and JSP

Servlets and JSP In this session, we will look at the Java technology called servlets, and see what they can do. Although they are an interesting idea, there is a serious problem associated with servlets that you need to be aware of – we will present the solution, a technology called 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 Static Web The World Wide Web, as it was originally designed, is a fairly static medium. The HyperText Transfer Protocol, or HTTP for short defines the general process for requesting web pages:

The client (web browser) requests a page from the server. The server responds by sending a stream of data back to the client.

Web Browser Clients Webserver - dishes out predefined webpages

1 : get

2 : webpage

Figure 19 - The HTTP Protocol simplified

43 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Making the Web Dynamic As the web matured, a demand grew for the web to become more dynamic. We have seen how Java Applets attempted to provide interactivity on the client side – but what if we want to do something dynamic on the server side?

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.

Figure 20 - A dynamic, constantly changing, message board

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.

44 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

The Servlet Solution A more recent solution, provided by Java (and J2EE) is to build small Java programs called servlets. These small programs are deployed and run on the server.

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.

Although this is a similar scheme to CGI, the main benefits are:

• We can use Java – a more serious and deep language than perl

• We can easily take advantage of Java’s features, such as JDBC

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.

public class HelloWorld extends HttpServlet

{

public void doGet()

{

out.println

(“<html><head><title>HelloWorld</title></head><body>");

out.println("<p>Hello to everyone! The time now is " +

(new java.util.Date()) + "</p>");

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

}

}

Figure 21 - An Example Servlet (many technical details omitted for clarity)

A Serious Problem Emerges The simple servlet above is all very well, but there is a major flaw in the idea behind servlets. In any non-trivial servlet, the code very rapidly becomes a nasty tangled combination of Application logic and HTML.

45 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

out.println ("<html><head><title>Extension List</title></head>");out.println ("<body><h1>Extension List</h1><hr><pre>");try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch (ClassNotFoundException e){

out.println ("An error occurred loading a driver:<p>");out.println ("<pre>" + e + "</pre>");

}

String url = "jdbc:odbc:PERSONELL";String user = "sysadmin";String pass = "sysadmin";Connection con = null

Figure 22 - A nasty combination of HTML and Java

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…

Java Server Programming (JSP) In JSP, instead of writing a Java Servlet, we write simple text files that look very much like standard HTML. Therefore, these files (called JSP files) should be relatively understandable to HTML coders. The difference is we are able to “drop in” small blocks of Java code anywhere in the file. These areas of Java are carefully delimited using some predefined markers.

Consider the following JSP file, a web page that outputs the date and time:

<html><head><title>What Time Is It?</title></head><body><h3>You requested this page on :

<%=new java.util.Date()%>

</h3></body></html>

<html><head><title>What Time Is It?</title></head><body><h3>You requested this page on :

<%=new java.util.Date()%>

</h3></body></html>

Figure 23 - A Simple JSP

46 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Figure 24 - The resulting output

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!

So in essence, JSP is a way of creating servlets without realising you’re writing servlets, and without their inherent complexity!

Here’s the process that goes on, step by step:

55

Client BrowserClient Browser

JavaServletJavaServlet

Source JSP File

Server

1

Source JSP FileSource JSP FileSource JSP File

Server

1

ServerServerServer

1

66HTML Page

6 6HTML Page

6 6

JavaCompiler

Servlet Classfile4 Java

CompilerServlet ClassfileJava

CompilerServlet Classfile

4Generated Java Servlet

3

Generated Java ServletGenerated Java Servlet

3

JSP Engine

2

JSP Engine

JSP Engine

2

Figure 25 - The JSP Architecture

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!)

47 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

Another Dynamic Webpage Here’s another example of a simple JSP. Again, we are demonstrating that we can drop lines of Java code anywhere we like in the HTML:

<html><head><title>First 10 Squares</title></head><body><h1>The First 10 Squares:</h1><hr>

<% for (int i=1; i<=10; i++) {

out.println (i*i);}

%>

<hr></body></html>

<html><head><title>First 10 Squares</title></head><body><h1>The First 10 Squares:</h1><hr>

<% for (int i=1; i<=10; i++) {

out.println (i*i);}

%>

<hr></body></html>

Figure 26 - Another simple JSP

Another Problem Emerges! You might have spotted that despite the nice, fluffy feel of JSP’s (and they are certainly at first glance more friendly than servlets), we actually haven’t solved the problems we identified in “A Serious Problem Emerges” (Page 44). We still have them, albeit in a different way.

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.

48 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

This is one of the biggest problems faced by many J2EE projects.

<%@ page import="java.sql.*" %><%

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch (ClassNotFoundException e){%>

<h1>An Error Occurred Loading a Driver</h1><% }

String url = "jdbc:odbc:PERSONELL";String user = "sysadmin";String pass = "sysadmin";Connection con = null;

try{

con = DriverManager.getConnection(url,user,pass);}catch (SQLException e){

%><h1>An error occurred connecting to the database</h1><hr><% }

<%@ page import="java.sql.*" %><%

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch (ClassNotFoundException e){%>

<h1>An Error Occurred Loading a Driver</h1><% }

String url = "jdbc:odbc:PERSONELL";String user = "sysadmin";String pass = "sysadmin";Connection con = null;

try{

con = DriverManager.getConnection(url,user,pass);}catch (SQLException e){

%><h1>An error occurred connecting to the database</h1><hr><% }

Figure 27 - An example of some very unpleasant looking JSP - what on earth is going on here??

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

49 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

The MVC Architecture What we have discussed here is one form of a system architecture known as the Model-View-Controller, or MVC. A discussion of MVC is beyond the scope of the course, but at a simple level, MVC simply says “use separate modules to handle the display, the system flow and the business logic” – which is roughly what we have done with our JSP’s and Servlets:

• The display logic is called the “View” in MVC.

• The system flow is called the “Controller “ in MVC.

• The business logic is called the “Module” in MVC.

It is imperative, to achieve success with J2EE on your project, to enforce this model.

Proj

ect

Stan

dard

JSP’s display results only. Servlets handle the Java logic.

The

“Controller”The “Model”

HTMLor JSP servlet Other Java

The“View”

Figure 28 - The Model View Controller (albeit in a simplified form)

Note – this method of design is often called “Model-2” in J2EE circles.

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.

50 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Generally, Java will be used:

• To display results – eg outputting the details of a product

• Simple loops – eg running through multiple products, and displaying each one in turn

• Minor cosmetic modifications to data – for example, turning a singular into a plural, changing a greeting depending on the time of day, etc.

The real problem is enforcement. There is nothing in Java or J2EE to prevent programmers from dropping huge blocks of code into JSP pages. We have seen this is a recipe for disaster – the only way to avoid it is to impose project standards and to carry out code inspections.

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

51 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

<i>The following items are in stock</i><pre>

<% Collection results =

(Collection)request.getAttribute("stockListResult");

Iterator it = results.iterator();while (it.hasNext()){

String next = (String)it.next();%>

Item : <%= next %>

<% } %>

<i>The following items are in stock</i><pre>

<% Collection results =

(Collection)request.getAttribute("stockListResult");

Iterator it = results.iterator();while (it.hasNext()){

String next = (String)it.next();%>

Item : <%= next %>

<% } %>

Figure 29 - JSP to display a stock list

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:

Using a Custom Tag The syntax of a custom tag is beyond the scope of this book15, but the following code illustrates the benefit of replacing the heavy Java in Figure 29:

<i>The following items are in stock</i><pre>

<c:forEach var=”item" items="$results">Item : <c:out value="${item}"/><br>

</c:forEach>

<i>The following items are in stock</i><pre>

<c:forEach var=”item" items="$results">Item : <c:out value="${item}"/><br>

</c:forEach>

Figure 30 - Replacing the Java with a Tag

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

52 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

JSP’s

• Servlets enable the dynamic creation of web pages

• JSP’s enable the creation of dynamic web pages as well, but rely much less on explicit Java coding

• The MVC or Model-2 must be enforced if maintainability and understandability is a requirement

• Custom Tags and the JSTL provide another way of hiding the Java in a JSP Page

53 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

The Purpose of Java Beans By assembling these Java Bean “Components” we can theoretically build applications without reinventing the wheel. Java Beans were originally envisaged to be graphical, but a Java Bean can actually be any Java Class, as long as it conforms to the “Design Patterns”.

54 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

Enterprise Java Beans The next stage of evolution of Java Beans was the development of Enterprise Java Beans, or EJB’s. EJB’s are essentially the same as standard Java Beans – they are small components that perform some kind of job.

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.

As an example, you might have a “Customer” EJB in an e-commerce application. This EJB would hold data about your customers, such as their credit rating and which products they are most likely to be interested in. As with any other Java Module, an EJB will be able to do things as well – for example we might be able to query the Customer EJB and find out the credit rating for each customer we are interested in.

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.

EJB’s are Persistent The data held inside an EJB can be made to be persistent – in other words, it can be stored on a relational database automatically. Any changes to the data in the bean will be reflected in the database, without the need for the programmer to write laborious (and error-prone) JDBC code (see “Databases in Java”, page 24).

The SQL required to perform the database transactions will be generated automatically by the deployment tool supplied by your application server (this SQL

55 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

can be tailored to your own needs if required, but it is done in the tool rather than polluting the Java code).

If required, persistence can be handled manually by the programmer. This would be necessary if particularly complex database persistence is required, but it does mean polluting the Java code with database/JDBC calls.

The terminology for the automatic persistence is “Container Managed Persistence”, or CMP – the manual variety is BMP.

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.

EJB’s are Transaction Aware EJB’s that hold data can be made to be transaction aware fairly easily. Either the programmer manually demarks regions of code that must be considered atomic, or entire methods (Java procedures) can be set to be a single transaction, using the deployment tool.

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.

Place Order Example As an example, consider an EJB that is responsible for placing an order for a customer. The EJB’s task is as in the following flow chart:

Place Order Use Case

Add order to orders list

Add invoice to the invoice queue

Send "order placed" message to customer

Credit Check Customer

ok?

Return Error Message

Use Case End

no

yes

Place Order Use Case

Add order to orders list

Add invoice to the invoice queue

Send "order placed" message to customer

Credit Check Customer

ok?

Return Error Message

Use Case End

no

yes

Place Order Use Case

Add order to orders list

Add invoice to the invoice queue

Send "order placed" message to customer

Credit Check Customer

ok?

Return Error Message

Use Case End

no

yes

Figure 32 - The Place Order Process

56 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

The automatic transaction handling is called “Container Managed Transactions” (CMT); the method using programmer intervention is called “Bean Managed Transactions” (BMT)

EJB’s are Distributed As we have seen, Enterprise Java Beans are located on a server and managed by the Application Server.

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!)

EJB’s are Multithreaded The Application Server manages threading automatically. As a quick example, assume a programmer has written an EJB called “Book” representing a product in an online book store. What happens if two customers try to get information about the book at the same time?

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.

57 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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

• Message Driven EJB’s (MDB)

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.

58 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

J2EE Design Patterns Designing and building J2EE systems is difficult. Or perhaps more accurately speaking, it is easy to design and build poor J2EE systems; applications that perform and scale badly.

Help is at hand. A collection of good design principles, called “Design Patterns” have been formulated by the J2EE community. Sun are making a big effort to collect and publish these design patterns – they are all available on-line at the Java website.

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].

Example Design Pattern Consider a simple system that allows the user to view a list of all customers in the database – and for each customer, their open purchase orders are also displayed.

Here is our first attempt at designing the application…

59 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

WebPage(JSP)

CustomerEJB

PurchaseOrder EJB

getCustomerDetails

getPODetails

Application ServerClient

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.

60 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

WebPage(JSP)

CustomerEJB

PurchaseOrder EJB

getCustomerDetails

getPODetails

Application ServerClient

ListCustomersSession EJB

listCustomers

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

• They automatically provide Distribution, Transactions, Multithreading and Persistence

• 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

• Use recognised “Design Patterns” when building your applications

16 This makes sense – recall we said that Session Beans usually do something rather than holding onto data

61 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

62 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

How the Tool Works The only requirement is that your programmers include a special kind of comment in their code, called javadoc comments. These comments are almost the same as standard comments (just a slightly different syntax).

In general, everything should be given a javadoc comment, such as the classes themselves, each item of data in the class, each function in the class – as much as is required to understand and maintain the class.

/** This class holds information about an* Employee in the company*/

public class Employee{

protected int salary;private String employeeCode;private Calendar dateOfJoining;…

}

/** This class holds information about an* Employee in the company*/

public class Employee{

protected int salary;private String employeeCode;private Calendar dateOfJoining;…

}

Figure 35 - A Java class with a javadoc comment

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.

63 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

Running the Tool When the tool is run, documentation is generated for the classes you wish to be documented (you can document your entire codebase in one single run if required). The output is a collection of indexed HTML files, in exactly the same format as the standard Java Help files (in fact, if you haven’t already guessed, javadoc is how the standard help is produced!).

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!).

Figure 36 - Javadoc help for the Employee class

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

• A drawback is that is does rather obscure the code a little!

64 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

65 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

On the subject of Object Orientation, although it is a standard and accepted method of analysing, designing and coding software, there is still a lot of misunderstanding, suspicion and confusion about OO.

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

66 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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?

67 An Introduction to Java and J2EE

© 2002 Ariadne Training Limited

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.

[2] : Hortstmann/Cornell. Core Java : Volume 1 Fundamentals Sun Microsystems/Prentice Hall An excellent tutorial covering a wide range of Java topics. Excellent examples and very well explained. The only drawback is a second volume is required to cover many of the advanced topics

[3] : Hortstmann/Cornell. Core Java : Volume 2 Advanced Features Sun Microsystems/Prentice Hall Another excellent volume, covering Threading, Collections and JDBC; in addition it covers Networking, Remote Objects, JavaBeans, Security, Java 2D, Internationalization, Native Methods and XML. It also goes into more detail on Swing.

[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.

[6] : Bond, Martin. Teach Yourself J2EE in 21 Days Sams We haven’t yet had a chance to review this book, but it is pleasing that at last programmer friendly books in the “Teach Yourself” vein are finally appearing for J2EE. As always, 21 days might be a bit optimistic though!

[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

[8] : Bayern, Shaun. 2002 JSTL In Action Manning Publications Co. A guide to the new JSTL