超级英雄通用礼包:Develop n-tier applications using J2EE--brief

来源:百度文库 编辑:九乡新闻网 时间:2024/07/07 16:17:13

Developn-tier applications using J2EE

Anintroduction to the Java 2 Platform, Enterprise Edition specification by way ofBEA's WebLogic Server

Javaoriginally made its debut in browsers and client machines; at the time, manyquestioned whether it was suitable for server-side development. Now, withincreasing third-party support for the Java 2 Platform, Enterprise Edition(J2EE), Java has become a widely accepted alternative for developingenterprise-strength server-side solutions. 

The J2EE platform consists of a set ofservices, application programming interfaces (APIs), and protocols that providethe functionality for developing multitiered Web-based applications.

In this article, we will examine the 13core technologies that make up J2EE: JDBC, JNDI, EJBs, RMI, JSP, Java servlets,XML, JMS, Java IDL, JTS, JTA, JavaMail, and JAF. We will describe where andwhen it is appropriate to use each technology; we will also describe how thedifferent technologies interact with each other.

Moreover, to give J2EE a real-world feel,we'll look at its main technologies in the context of WebLogic Server, a widelyused J2EE implementation from BEA Systems. With that in mind, this introductoryarticle will be of interest to developers new to WebLogic Server and J2EE, as wellas project managers and business analysts with an interest in understandingwhat J2EE has to offer.

The bigpicture: Distributed architectures and J2EE

In the past, two-tierapplications -- alsoknown as client/server applications -- were commonplace. Figure 1illustrates the typical two-tier architecture. In some cases, the only serviceprovided by the server was that of a database server. In those situations, theclient was then responsible for data access, applying business logic,converting the results into a format suitable for display, displaying theintended interface to the user, and accepting user input. The client/serverarchitecture is generally easy to deploy at first, but is difficult to upgradeor enhance, and is usually based on proprietary protocols -- typicallyproprietary database protocols. It also makes reuse of business andpresentation logic difficult, if not impossible. Finally, and perhaps mostimportant in the era of the Web, two-tier applications typically do not provevery scalable and are therefore not well suited to the Internet.

Figure 1.Two-tier application architecture

 

Sun designed J2EE in part to address thedeficiencies of two-tier architectures. As such, J2EE defines a set ofstandards to ease the development of n-tier enterprise applications. Itdefines a set of standardized, modular components; provides a complete set ofservices to those components; and handles many details of application behavior-- such as security and multithreading -- automatically.

Using J2EE to develop n-tierapplications involves breaking apart the different layers in the two-tierarchitecture into multiple tiers. An n-tier application could provide separatelayers for each of the following services:

·                         Presentation: In a typical Web application, a browser runningon the client machine handles presentation.

·                         Dynamically generated presentation: Although a browser could handle some dynamicallygenerated presentation, for the widest support of different browsers much ofthe action should be done on the Web server using JSPs, servlets, or XML(Extensible Markup Language) and XSL (Extensible Stylesheet Language).

·                         Business logic: Business logic is best implemented in SessionEJBs (described later).

·                         Data access: Data access is best implemented in Entity EJBs(described later) and using JDBC.

·                         Backend system integration: Integration with backend systems may use avariety of technologies. The best choice will depend upon the exact nature ofthe backend system.

 

You may begin to wonder: why have so manylayers? Well, the layered approach makes for a more scalable enterpriseapplication. It allows each layer to focus on a specific role -- for example,allowing a Web server to serve Webpages, an application server to serveapplications, and a database server to serve databases.

Because it's built on top of the Java 2Platform, Standard Edition (J2SE), J2EE provides all the same advantages andfeatures of J2SE. These include "Write Once, Run Anywhere"portability, JDBC for database access, CORBA technology for interaction withexisting enterprise resources, and a proven security model. Building on thisbase, J2EE then adds support for Enterprise JavaBean (EJB) components, Javaservlets, JavaServer Pages (JSPs), and XML technology.

Distributedarchitectures with WebLogic Server

J2EE provides a framework -- a standardAPI -- for developing distributed architectures. The implementation of anengine to implement this framework is left up to third-party vendors. Somevendors will focus on particular components of the overall J2EE architecture.For example, Apache's Tomcat provides support for JSPs and servlets. BEASystems provides a fuller implementation of the J2EE specification with itsWebLogic Server product.

By providing a complete implementation ofthe J2EE specifications, WebLogic Server makes it easy to build and deployscalable, distributed applications. WebLogic Server and J2EE handle certaincommon programming tasks for you. These include the provision of transactionservices, security realms, guaranteed messaging, naming and directory services,database access and connection pooling, thread pooling, load balancing, andfault tolerance.

By providing these common services in aneasy-to-use and standard way, products like WebLogic Server provide morescalable and maintainable applications. The result is increased availability ofthose applications to a larger number of users.

The J2EEtechnologies

In the following sections, we'll describeeach of the technologies making up J2EE, and see how WebLogic Server supportsthem in a distributed application. Perhaps the most commonly used J2EEtechnologies include JDBC, JNDI, EJB, JSPs, and servlets, upon which wetherefore focus our attention.

Figure 2 illustrates where each of theJ2EE technologies are most commonly used within a distributed application.

Figure 2. Asample n-tier application architecture

 

Java DatabaseConnectivity (JDBC)

The JDBC API accesses a variety ofdatabases in a uniform way. Like ODBC, JDBC hides proprietary database issuesfrom the developer. Because it's built on Java, JDBC also is able to provideplatform-independent access to databases.

JDBC defines four fundamentally differenttypes of drivers, as we'll see next.

Type 1: JDBC-ODBC Bridge

The JDBC-ODBC Bridgeproved most useful when JDBC was still in its infancy. With it, developers canuse JDBC to access an ODBC data source. As a downside, it requires that an ODBCdriver be installed on the client machine which, generally speaking, should berunning a version of Microsoft Windows. By using this type of driver, you thereforesacrifice the platform independence of JDBC. Additionally, the ODBC driverrequires client-side administration.

Type 2: JDBC-nativedriver bridge

The JDBC-native driver bridge provides aJDBC interface built on top of a native database driver -- without using ODBC.The JDBC driver converts standard JDBC calls into native calls to the API ofthe database. Using a type 2 driver also sacrifices the platform independenceof JDBC and requires installation of client-side native code.

Type 3: JDBC-networkbridge

JDBC-network bridge drivers remove theneed for client-side database drivers. They make use of network-servermiddleware to access a database. This makes such techniques as load balancing,connection pooling, and data caching possible. Because type 3 drivers ofteninvolve a relatively small download time, are platform independent, and requireno client-side installation or administration, they are good for Internetapplications.

Type 4: Pure Javadriver

Type 4 provides direct database accessusing a pure Java database driver. Due to the way type 4 drivers run on theclient and directly access a database, running in this mode would imply atwo-tier architecture. A better use of type 4 drivers in an n-tierarchitecture would be to have an EJB contain the data access code, and havethat EJB provide a database-independent service to its clients.

WebLogic Server provides JDBC drivers forsome of the more common databases, including Oracle, Sybase, Microsoft SQLServer, and Informix. It also comes with a JDBC driver for Cloudscape, a pureJava DBMS, an evaluation copy of which comes with WebLogic Server.

Next, let's look at an example.

JDBC Example

Our exampleassumes that you have a PhoneBook database set up in Cloudscape, and that thisdatabase contains a table CONTACT_TABLEwith fields NAME and PHONE. We begin by loading the Cloudscape JDBCdriver, and requesting that the driver manager obtain a connection to thePhoneBook Cloudscape database. Using this connection, we construct a Statement object anduse it to execute a simple SQL query. Finally, the loop iterates through allentries in the result set, writing the contents of the NAME and PHONE fields to thestandard output.

import java.sql.*;
public class JDBCExample
  {
  public static void main( String args[] )
    {
    try
      {
      Class.forName("COM.cloudscape.core.JDBCDriver");
      Connection conn = DriverManager.getConnection("jdbc:cloudscape:PhoneBook");
      Statement stmt = conn.createStatement();
      String sql = "SELECT name, phone FROM CONTACT_TABLE ORDER BY name";
      ResultSet resultSet = stmt.executeQuery( sql );
      String name;
      String phone;
      while ( resultSet.next() )
        {
        name = resultSet.getString(1).trim();
        phone = resultSet.getString(2).trim();
        System.out.println( name + ", " + phone );
        }
      }
    catch ( Exception e )
      {
      // Handle exception here
      e.printStackTrace();
      }
    }
  }

 

That's all there is to it. Next, let'slook at the use of JDBC in enterprise applications.

JDBC in enterpriseapplications

The previous example is, by necessity,somewhat trivial. It also assumes a two-tier architecture. In an n-tierenterprise application, it is much more likely that the client will communicatewith an EJB, which, in turn, will make the database connection. To enableimproved scalability and performance, WebLogic Server provides support forconnection pools.

Connectionpools reduce the overhead of establishing and destroying database connectionsby creating a pool of database connections when the server starts up. When aconnection to the database is subsequently required, WebLogic Server simplyselects one from the pool rather than creating one from scratch. Connectionpools in WebLogic Server are defined in the weblogic.properties file. (Refer to theexamples in your weblogic.properties file and the WebLogicServer documentation for more information.)

Anotherdatabase feature frequently required in enterprise applications is support fortransactions. A transaction is a group of statements that should be treated asa single statement to ensure data integrity. JDBC uses the auto-commit transactionmode by default. This can be overridden using the setAutoCommit() method of the Connection class.

Now that we have a sense of JDBC, let'sturn our attention to JNDI.

Java Namingand Directory Interface (JNDI)

The JNDI API is used to access naming anddirectory services. As such, it provides a consistent model for accessing andmanipulating such enterprise-wide resources as DNS, LDAP, local filesystems, orobjects in an application server.

In JNDI,every node in a directory structure is called a context. Every JNDI name is relative to acontext; there is no notion of an absolute name. An application can obtain itsfirst context using theInitialContext class:

Context ctx = new InitialContext();

 

From thisinitial context, the application can traverse the directory tree to locate thedesired resources or objects. For example, assume that you have deployed an EJBwithin WebLogic Server and bound the home interface to the name myApp.myEJB. A client of this EJB, after obtainingan initial context, could then locate the home interface using:

MyEJBHome home = ctx.lookup( "myApp.myEJB" );

 

Once you have a reference to the acquiredobject -- in this case, the home interface of the EJB -- it is then possible toinvoke methods on it. We will discuss this further in the section belowentitled "Enterprise Java Beans."

The above discussion of JNDI is just thetip of the iceberg. In addition to looking up objects in a context, JNDI alsoprovides methods to:

·                         Insert, or bind, an object into a context. Thisis effectively what you do when you deploy an EJB.

·                         Remove an object from a context.

·                         List all objects within a context.

·                         Create and delete subcontexts.

 

Next, let's turn our attention to EJBs.

Enterprise Java Beans(EJB)

One of the J2EE technologies to receive agreat deal of media attention is EJBs. They provide a framework for developingand deploying distributed business logic to clients, thereby significantlyeasing the development of scalable, highly complex enterprise applications. TheEJB specification defines how and when EJB components should interact withtheir container. It is the responsibility of the container to provide forcommon services, such as directory services, transaction management, security,resource pooling, and fault tolerance.

The EJBs specification defines threefundamental types of bean:

·                         Stateless session beans: Theseprovide a single-use service, do not maintain any state, do not survive servercrashes, and are relatively short lived. For example, a stateless session beanmay be used to perform temperature conversion.

·                         Stateful session bean: These provide a conversational interaction withthe client and, as such, store state on the behalf of the client. An onlineshopping cart is a classic example of a stateful session bean. Stateful sessionbeans do not survive server crashes, are also relatively short lived, and eachinstance can be used only by a single thread.

·                         Entity beans: These provide a representation of persistentdata -- typically stored in a database -- and can therefore survive a servercrash. Multiple clients can use EJBs that represent the same data. An exampleof an entity EJB: a customer's account information.

 

In spite of their differences, all EJBshave much in common. They all possess a home interface that defines how aclient can create and destroy the EJB; a remote interface that defines themethods a client can invoke on the bean; and a bean class that implements themain business logic.

Describing how to develop an EJB isbeyond the scope of this article. However, once an EJB has been developed orpurchased from a third party, it must be deployed in your application server.WebLogic Server 5.1 comes with an EJB Deployer Tool to assist with deploymentof EJBs. When you deploy an EJB using the EJB Deployer Tool, you specify theJNDI name used by clients to locate the EJB. The Deployer Tool will thengenerate wrapper classes to handle communications with the container and bundlethe required Java classes together in a jar file.

Once an EJBhas been deployed, a client can locate the EJB using its JNDI name. First, itmust obtain a reference to the home interface. Then, using that interface, theclient can invoke one of the bean's create() methods to obtain ahandle to a bean instance running on the server. Finally, the client may usethis handle to invoke methods on the bean.

From EJBs, we shift to JSPs.

JavaServerPages (JSPs)

Some of you may already be familiar withMicrosoft's Active Server Pages (ASPs); JSPs are the platform-independentequivalent. They were designed to help Web content developers create dynamicWebpages with relatively little coding. Web designers who don't know how toprogram can use JSPs to create dynamic pages. A JavaServer Page consists ofHTML code interspersed with Java code. The server processes the Java code whenthe page is requested by the client, returning the generated HTML page to thebrowser.

Let's look ata simple example of a JSP that displays the server's current date and time. Anexplanation of the details of this is beyond the scope of this article;however, note the Java code between the<% and %> symbols,followed by the Java expression between the <%=and %> symbols.

 Sample JSP Page

Date JSP sample

<% response.setHeader("Refresh", 5); %>
The current date is <%= new Date()  %>.

 

You mayoccasionally hear reference to JHTML, an older standard since superseded byJSPs. WebLogic Server can support JSPs as well as JHTML. Note that, by default,JSPs are not enabledwithin WebLogic Server. To enable them, you must edit the weblogic.properties file and enable the Webserver -- if it hasn't already been enabled -- as well as the JSPServlet.

Next up: Java servlets

Java servlets

A servlet provides much the samefunctionality as a JSP, albeit by taking a somewhat different approach. WhereasJSPs typically consist mostly of HTML code interspersed with small amounts ofJava code, servlets, on the other hand, are written totally in Java and produce HTML code.

A servlet is a small Java program thatextends the functionality of a Web server. It is a server-side applicationdynamically executed when requested, much like CGI Perl scripts in moretraditional Web servers. One of the major differences between CGI scripts andservlets: CGI scripts require a whole new process to be started -- incurringadditional overhead -- whereas servlets are executed as a separate threadwithin the servlet engine. Servlets therefore tend to offer improvedscalability.

Whendeveloping servlets, you will generally want to extend thejavax.servlet.http.HttpServlet class, and override someof its methods. The methods of most interest include:

·                         service(): Acts as a dispatcher to command-specificmethods

·                         doGet(): Handles an HTTP GET request from a client

·                         doPost(): Handles an HTTP POST request from a client

 

Other methods exist to handle differenttypes of HTTP requests -- refer to the HttpServlet API documentation for moreinformation (seeResources).

The methodsdescribed above are all part of the standard J2EE Servlet API. WebLogic Serverprovides a full implementation of this API. Once you have developed yourservlet, you can deploy it in WebLogic Server by registering it in the weblogic.properties file.

With Java servlets, we've reached the endof J2EE's major technologies, but that's not the end to what J2EE has to offer.In the next sections, we'll take a brief look at the remaining technologies,including RMI, Java IDL and CORBA, JTA, and XML, to name a few.

Remote MethodInvocation (RMI)

As its name suggests, the RMI protocolinvokes methods on remote objects. It uses serialization to pass data betweenthe client and the server. RMI is the underlying protocol used by EJBs.

Java IDL/CORBA

With Java's IDL support, developers canintegrate Java with CORBA. They can create Java objects that can be deployedwithin a CORBA ORB, and they can create Java classes that act as clients toCORBA objects deployed within other ORBs. The latter approach provides anotherway in which Java can be used to integrate your new application with legacysystems.

JavaTransaction Architecture (JTA)/Java Transaction Service (JTS)

JTA defines a standard API thatapplications can use to access transaction monitors.

JTS is a basic implementation of a CORBAOTS transaction monitor. JTS specifies the implementation of a TransactionManager that supports the Java Transaction API (JTA) specification at a highlevel and implements the Java mapping of the OMG OTS specification at a lowlevel. A JTS Transaction Manager provides transaction services to theapplication server, the resource manager, standalone applications, and theCommunications Resource Manager.

JavaMail andJavaBeans Activation Framework

JavaMail is an API for accessing mailservers. The JavaMail API provides a set of abstract classes that model a mailsystem. Both SMTP and IMAP servers are supported.

JavaMail makes use of the JavaBeansActivation Framework (JAF) to handle MIME-encoded mail attachments. MIME bytestreams can be converted to and from Java objects. Most applications will nothave to use JAF directly.

Java MessagingService (JMS)

JMS is an API for communicating withmessage-oriented middleware. It supports both the point-to-point domain and thepublish/subscribe domain, and provides support for guaranteed message delivery,transactional message delivery, persistent messages, and durable subscribers.JMS provides another way of integrating your application with legacy backendsystems.

ExtensibleMarkup Language (XML)

XML is a language for defining othermarkup languages. It can be used to share data between businesses. XML wasdeveloped independently from Java; however, it shares similar goals in that itis platform independent. By combining Java with XML, you have a completelyplatform-independent solution. Various companies are working on developing atight integration between Java and XML. For more information, visit Sun'sJava-XML page, or the XML Zone at IBM's developerWorks (see Resources forthe URLs).

Conclusion

In this article, we introduceddistributed architectures built upon J2EE, and we described WebLogic Server'ssupport for J2EE. This, however, is just the tip of the iceberg, as no 3,000word article could begin to do justice to J2EE's potential impact on yourenterprise applications.

We focused our attention on thetechnologies that you are most likely to encounter when you begin working withJ2EE: JDBC, JNDI, EJBs, JSPs, and servlets. We also provided you with somebackground information on the less well-known J2EE technologies. Whether youare a developer, business analyst, or project manager, you now should have agood idea of what J2EE and WebLogic Server have to offer you, your enterprise,and your enterprise applications.