home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    


Chapter 17. Java 2, Enterprise Edition

The specification for the Java 2, Enterprise Edition ( J2EE) defines a platform for developing web-enabled applications that includes Enterprise JavaBeans, servlets, and JavaServer Pages ( JSP). J2EE products are application servers that provide a complete implementation of the EJB, servlet, and JSP technologies. In addition, the J2EE outlines how these technologies work together to provide a complete solution. To help you understand J2EE, we must introduce servlets and JSP and explain the synergy between these technologies and Enterprise JavaBeans.

At the risk of spoiling the story, J2EE provides two kinds of "glue" to make it easier for components to interact. We have already seen both types of glue. First, the JNDI enterprise naming context (ENC) is used to standardize the way components look up resources they need. We have already seen the ENC in the context of enterprise beans; in this chapter, we will look briefly at how servlets, JSPs, and even some clients can use the ENC to find resources. Second, the use of deployment descriptorsin particular, the use of XML to define a language for deployment descriptorshas been extended to servlets and JSP. Java servlets and JSP pages can be packaged with deployment descriptors that define their relationships to their environment. Deployment descriptors are also used to define entire assemblies of many components into applications.

17.1 Servlets

The servlet specification defines a server-side component model that can be implemented by web server vendors. Servlets provide a simple but powerful API for generating web pages dynamically. (Although servlets can be used for many different request-response protocols, they are predominantly used to process HTTP requests for web pages.)

Servlets are developed in the same fashion as enterprise beans; they are Java classes that extend a base component class and have a deployment descriptor. Once a servlet is developed and packaged in a JAR file, it can be deployed in a web server. When a servlet is deployed, it is assigned to handle requests for a specific web page or to assist other servlets in handling page requests. The following servlet, for example, might be assigned to handle any request for the helloworld.html page on a web server:

import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse response) 
        throws ServletException,java.io.IOException {

    try {
        ServletOutputStream writer = response.getWriter();
        writer.println("<h1>Hello World!!</h1>");
    } catch(Exception e) {
        // handle exception

When a browser sends a request for the page to the web server, the server delegates the request to the appropriate servlet instance by invoking the servlet's doGet() method.[1] The servlet is provided with information about the request in the HttpServletRequest object and can use the HttpServletResponse object to reply to the request. This simple servlet sends a short HTML document including the text "Hello World" back to the browser, which displays it. Figure 17-1 illustrates how a request is sent by a browser and serviced by a servlet running in a web server.

Figure 17-1. Servlet servicing an HTTP request


Servlets are similar to session beans because they both perform a service and can directly access backend resources (e.g., databases) through JDBC, but they do not represent persistent data. Servlets do not, however, have support for container-managed transactions and are not composed of business methods. Servlets deal with very specific (usually HTTP) requests and respond by writing to an output stream.

The servlet specification is extensive and robust but also simple and elegant. It is a powerful server-side component model. You can learn more about servlets by reading Java Servlet Programming by Jason Hunter and William Crawford (O'Reilly).

17.2 JavaServer Pages

JavaServer Pages is an extension of the servlet component model that simplifies the process of generating HTML dynamically. JSP essentially allows you to incorporate Java directly into an HTML page as a scripting language. In J2EE, the Java code in a JSP page can access the JNDI ENC, just like the code in a servlet. In fact, JSP pages (text documents) are translated and compiled into Java servlets, which are then run in a web server just like any other servletsome servers do the compilation automatically at runtime. You can also use JSP to generate XML documents dynamically.

You can learn more about JSP by reading JavaServer Pages by Hans Bergsten (O'Reilly).

17.3 Web Components and EJB

Together, servlets and JSP provide a powerful platform for generating web pages dynamically. Servlets and JSP, which are collectively called web components, can access resources like JDBC and enterprise beans. Because web components can access databases using JDBC, they can provide a powerful platform for e-commerce by allowing an enterprise to expose its business systems to the Web through an HTML interface. HTML has several advantages over more conventional client applications, in Java or any other language. The most important advantages have to do with distribution and firewalls. Conventional clients need to be distributed and installed on client machines, which is their biggest limitation: they require additional work for deployment and maintenance. Applets, which are dynamically downloaded, can be used to eliminate the headache of installation, but applets have other limitations, such as sandbox restrictions and heavyweight downloads. In contrast, HTML is extremely lightweight, does not require prior installation, and does not suffer from security restrictions. In addition, HTML interfaces can be modified and enhanced at their source without having to update the clients.

Firewalls present another significant problem in e-commerce. HTTP, the protocol over which web pages are requested and delivered, can pass through most firewalls without a problem, but other protocols such as IIOP or JRMP cannot. This restriction has proven to be a significant barrier to the success of distributed object systems that must support access from anonymous clients, because it means that distributed object applications generally cannot be created for a client base that may have arbitrary firewall configurations. HTTP does not have this limitation, since practically all firewalls allow HTTP to pass unhindered.

The problems with distribution and firewalls have led the EJB industry to adopt, in large part, an architecture based on the collaborative use of web components (servlets/JSP) and Enterprise JavaBeans. While web components provide the presentation logic for generating web pages, EJB provides a robust transactional middle tier for business logic. Web components access enterprise beans using the same API as application clients. Each technology is doing what it does best: servlets and JSP are excellent components for generating dynamic HTML, while EJB is an excellent platform for transactional business logic. Figure 17-2 illustrates how this architecture works.

Figure 17-2. Using servlets/JSP and EJB together


This web component-EJB architecture is so widely accepted that it begs the question, "Should there be a united platform?" This is the question the J2EE specification is designed to answer. The J2EE specification defines a single application server platform that focuses on the interaction between servlets, JSP, and EJB. J2EE is important because it provides a specification for the interaction of web components with enterprise beans, making solutions more portable across vendors that support both component models.

17.4 J2EE Fills in the Gaps

The J2EE specification attempts to fill the gaps between the web components and Enterprise JavaBeans by defining how these technologies come together to form a complete platform.

One of the ways in which J2EE adds value is by creating a consistent programming model across web components and enterprise beans through the use of the JNDI ENC and XML deployment descriptors. A servlet in J2EE can access JDBC DataSource objects, environment entries, and references to enterprise beans through a JNDI ENC in exactly the same way that enterprise beans use the JNDI ENC. To support the JNDI ENC, web components have their own XML deployment descriptor that declares elements for the JNDI ENC (<ejb-ref>, <resource-ref>, <env-entry>) as well security roles and other elements specific to web components. In J2EE, web components are packaged along with their XML deployment descriptors and deployed in JAR files with the extension .war, which stands for web archive. The use of the JNDI ENC, deployment descriptors, and JAR files in web components makes them consistent with the EJB programming model and unifies the entire J2EE platform.

Use of the JNDI ENC makes it much simpler for web components to access Enterprise JavaBeans. The web component developer does not need to be concerned with the network location of enterprise beans; the server will map the <ejb-ref> elements listed in the deployment descriptor to the enterprise beans at deployment time.

Optionally, J2EE vendors can allow web components to access the EJB 2.0 local component interfaces of enterprise beans. This makes a lot of sense if the web component and the bean are co-located in the same Java Virtual Machine, because the Java RMI-IIOP semantics can improve performance. It's expected that most J2EE vendors will support this option.

The JNDI ENC also supports access to a javax.jta.UserTransaction object, as is the case in EJB. The UserTransaction object allows the web component to manage transactions explicitly. The transaction context must be propagated to any enterprise beans accessed within the scope of the transaction (according to the transaction attribute of the enterprise bean method). A .war file can contain several servlets and JSP documents, which share an XML deployment descriptor.

J2EE also defines an .ear (enterprise archive) file, which is a JAR file for packaging EJB JAR files and web component JAR files (.war files) together into one complete deployment called a J2EE application. A J2EE application has its own XML deployment descriptor that points to the EJB and web component JAR files (called modules) as well as other elements such as icons, descriptions, and the like. When a J2EE application is created, interdependencies such as <ejb-ref> and <ejb-local-ref> elements can be resolved and security roles can be edited to provide a unified view of the entire web application. Figure 17-3 illustrates the file structure inside a J2EE archive file.

Figure 17-3. Contents of a J2EE EAR file


17.4.1 J2EE Application Client Components

In addition to integrating web and enterprise bean components, J2EE introduces a completely new component model: the application client component. An application client component is a Java application that resides on a client machine and accesses enterprise bean components on the J2EE server. Client components also have access to a JNDI ENC that operates the same way as the JNDI ENC for web and enterprise bean components. The client component includes an XML deployment descriptor that declares the <env-entry>, <ejb-ref>, and <resource-ref> elements of the JNDI ENC in addition to a <description>, <display-name>, and <icon> that can be used to represent the client component in a deployment tool.

A client component is simply a Java program that uses the JNDI ENC to access environment properties, enterprise beans, and resources ( JDBC, JavaMail, etc.) made available by the J2EE server. Client components reside on the client machine, not the J2EE server. Here is an extremely simple component:

public class MyJ2eeClient {
    public static void main(String [] args) {
        InitialContext jndiCntx = new InitialContext();
        Object ref = jndiCntx.lookup("java:comp/env/ejb/ShipBean");
        ShipHome home = (ShipHome)
        Ship ship = home.findByPrimaryKey(new ShipPK(1));
        String name = ship.getName();


MyJ2eeClient illustrates how a client component is written. Notice that the client component did not need to use a network-specific JNDI InitialContext. In other words, we did not have to specify the service provider in order to connect to the J2EE server. This is the real power of the J2EE application client component: location transparency. The client component does not need to know the exact location of the Ship EJB or choose a specific JNDI service provider; the JNDI ENC takes care of locating the enterprise bean.

When application components are developed, an XML deployment descriptor is created that specifies the JNDI ENC entries. At deployment time, a vendor-specific J2EE tool generates the class files needed to deploy the component on client machines.

A client component is packaged into a JAR file with its XML deployment descriptor and can be included in a J2EE application. Once a client component is included in the J2EE application deployment descriptor, it can be packaged in the EAR file with the other components, as Figure 17-4 illustrates.

Figure 17-4. Contents of a J2EE EAR file with application component


17.4.2 Guaranteed Services

The J2EE 1.3 specification requires application servers to support a specific set of protocols and Java enterprise extensions. This requirement ensures a consistent platform for deploying J2EE applications. J2EE application servers must provide the following "standard" services:

Enterprise JavaBeans 2.0

J2EE products must support the complete specification.

Servlets 2.3

J2EE products must support the complete specification.

JavaServer Pages 1.2

J2EE products must support the complete specification.


Web components in a J2EE server service both HTTP and HTTPS requests. The J2EE product must be capable of advertising HTTP 1.0 and HTTPS (HTTP 1.0 over SSL 3.0) on ports 80 and 443, respectively.


Support for Java RMI-IIOP is required. However, other protocols may also be used by the vendor, as long as they are compatible with Java RMI-IIOP semantics.


J2EE components can be Java RMI-JRMP clients.


Web components and enterprise beans must be able to access CORBA services hosted outside the J2EE environment using JavaIDL, a standard part of the Java 2 platform.

JDBC 2.0

J2EE requires support for the JDBC Core ( JDK 1.3) and some parts of the JDBC 2.0 Extension, including connection naming and pooling and distributed transaction support.

Java Naming and Directory Interface ( JNDI) 1.2

Web and enterprise bean components must have access to the JNDI ENC, which make available EJBHome objects, JTA UserTransaction objects, JDBC DataSource objects, and Java Message Service connection factory objects.

JavaMail 1.2 and JAF 1.0

J2EE products must support sending basic Internet mail messages (the protocol is not specified) using the JavaMail API from web and enterprise bean components. The JavaMail implementation must support MIME message types. JAF is the Java Activation Framework, which is needed to support different MIME types and is required for support of JavaMail functionality.

Java Message Service ( JMS) 1.0.2

J2EE products must provide support for both point-to-point (p2p) and publish-and-subscribe (pub/sub) messaging models.

Java API for XML Parsing ( JAXP) 1.1

J2EE products must support JAXP and provide at least one SAX 2 parser, at least one DOM 2 parser, and at least one XSLT transform engine.

J2EE Connector Architecture ( JCA) 1.0

J2EE must support the JCA API from all components and provide full support for resource adapters and transaction capabilities as defined by the JCA.

Java Authentication and Authorization Service ( JAAS) 1.0

J2EE products must support the use of JAAS as described in the JCA specification. In addition, application client containers must support the authentication facilities defined in the JAAS specification.

Java Transaction API 1.0.1

Web and enterprise bean components must have access to JTA UserTransaction objects via the JNDI ENC under the "java:comp/UserTransaction" context. The UserTransaction interface is used for explicit transaction control.

17.5 Fitting the Pieces Together

To illustrate how a J2EE platform would be used, imagine using a J2EE server in Titan's reservation system. To build this system, we would use the TravelAgent, Cabin, ProcessPayment, Customer, and other enterprise beans we defined in this book, along with web components that would provide an HTML interface.

The web components would access the enterprise beans in the same way that any Java client would, by using the enterprise beans' remote and home interfaces. The web components would generate HTML to represent the reservation system.

Figure 17-5 shows a web page generated by a servlet or JSP page for the Titan reservation system. This web page was generated by web components on the J2EE server. At this point, the person using the reservation system has been guided through a login page, a customer selection page, and a cruise selection page and is about to choose an available cabin for the reservation.

Figure 17-5. HTML interface to the Titan reservation system


The list of available cabins was obtained from the TravelAgent EJB, whose listAvailableCabins() method was invoked by the servlet that generated the web page. The list of cabins was used to create an HTML list box in a web page that was loaded into the user's browser. When the user chooses a cabin and submits the selection, an HTTP request is sent to the J2EE server. The J2EE server receives the request and delegates it to the ReservationServlet, which invokes the TravelAgent.bookPassage() method to do the actual reservation. The ticket information returned by the bookPassage() method is then used to create another web page, which is sent back to the user's browser. Figure 17-6 shows how the different components work together to process this request.

Figure 17-6. J2EE Titan reservation system


17.6 Future Enhancements

Several areas are targeted for improvement in the next major release of the J2EE specification. Support for "web services" is expected to be a larger part of the J2EE specification in the future, including support for Java API for XML Messaging ( JAXM), Java API for XML Registries ( JAXR), and Java API for XML RPC ( JAX-RPC). Support for the XML Data Binding API, which considered easier to use than JAXP, may also be required in a future version of the specification.

In addition, J2EE may be expanded to require support for JDBC rowsets, SQLJ, management and deployment APIs, and possibly a J2EE SPI that would build on the advancements made with the JCA specification.

[1]  HttpServlets also have a doPost() method that handles requests for forms.