1. Trang chủ
  2. » Công Nghệ Thông Tin

The J2EETM Tutorial doc

350 156 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề The J2EETM Tutorial
Tác giả Stephanie Bodoff, Dale Green, Eric Jendrock, Monica Pawlan, Beth Stearns
Trường học Sun Microsystems, Inc.
Chuyên ngành Computer Science
Thể loại Tutorial
Năm xuất bản 2001
Thành phố Palo Alto
Định dạng
Số trang 350
Dung lượng 11,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Distributed Multitiered Applications 24J2EE Application Components 25Client Components 26Thin Clients 28Web Components 28Business Components 29Enterprise Information System Tier 30J2EE A

Trang 1

The J2EE TM Tutorial

Stephanie Bodoff

Dale Green Eric Jendrock Monica Pawlan Beth Stearns

Trang 2

Copyright © 2001 by Sun Microsystems, Inc.

901 San Antonio Road, Palo Alto, California 94303 U.S.A.

All rights reserved.

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013(c)(1)(iii) and FAR 52.227-19.

The release described in this book may be protected by one or more U.S patents, foreign patents, or pending applications.

Sun, Sun Microsystems, Sun Microsystems Computer Corporation, the Sun logo, the Sun Microsystems Computer Corporation logo, Java, JavaSoft, Java Software, JavaScript, JDBC, JDBC Compliant, JavaOS, JavaBeans, Enterprise JavaBeans, JavaServer Pages, J2EE, J2SE, JavaMail, Java Naming and Directory Interface, EJB, and JSP are trademarks or registered trademarks of Sun Microsystems, Inc UNIX®is a registered trademark in the United States and other countries, exclusively licensed through X/Open Com- pany, Ltd All other product names mentioned herein are the trademarks of their respective owners THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION SUN MICROSYSTEMS, INC MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PROD- UCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

Trang 3

Contents

Preface xvii

Who Should Use This Tutorial xvii

About the Examples xviii

Prerequisites for the Examples xviii

Where to Find the Examples xviii

How to Build and Run the Examples xviii

Related Information xx

How to Print This Tutorial xxi

Typographical Conventions xxi

Acknowledgments xxii

Chapter 1: Overview 23

Distributed Multitiered Applications 24

J2EE Application Components 25

Client Components 26

Application Clients 26

Web Browsers 26

Applets 26

JavaBeans™ Component Architecture 27

J2EE Server Communications 27

Thin Clients 28

Web Components 28

Business Components 29

Enterprise Information System Tier 30

J2EE Architecture 30

Containers and Services 30

Container Types 32

Packaging 33

Trang 4

Development Roles 34

J2EE Product Provider 34

Tool Provider 34

Application Component Provider 35

Enterprise Bean Creation 35

Web Component Creation 35

J2EE Application Client Creation .35

Application Assembler .35

Application Deployer and Administrator .36

Reference Implementation Software .36

Web Server .37

Database Access .37

J2EE APIs 37

Enterprise JavaBeans Technology 2.0 37

JDBC™ 2.0 API 38

Java Servlet Technology 2.3 .38

JavaServer Pages (JSP) Technology 1.2 .38

Java Message Service (JMS) 1.0 39

Java Transaction API (JTA) 1.0 39

JavaMail™ Technology 1.2 39

JavaBeans Activation Framework 1.0 39

Java API for XML (JAXP) 1.1 39

J2EE Connector API 1.0 .40

Java Authentication and Authorization Service (JAAS) 1.0 40

Tools 40

Application Deployment Tool 40

Scripts 42

Chapter 2: Getting Started 43

Setting Up 44

Getting the Example Code 44

Building the Example 44

Checking the Environment Variables 45

Starting the J2EE™ Server 45

Starting thedeploytool .45

Creating the J2EE™ Application 46

Creating the Enterprise Bean 46

Coding the Enterprise Bean 46

Coding the Remote Interface 46

Coding the Home Interface .47

Coding the Enterprise Bean Class 47

Compiling the Source Files 48

Packaging the Enterprise Bean 48

Trang 5

Creating the J2EE™ Application Client 49

Coding the J2EE Application Client 50

Locating the Home Interface 50

Creating an Enterprise Bean Instance 51

Invoking a Business Method 51

ConverterClient Source Code 51

Compiling the Application Client 52

Packaging the J2EE Application Client 52

Specifying the Application Client’s Enterprise Bean Reference 53

Creating the Web Client 53

Coding the Web Client 53

Compiling the Web Client 55

Packaging the Web Client 55

Specifying the Web Client’s Enterprise Bean Reference 56

Specifying the JNDI Name 56

Deploying the J2EE™ Application 57

Running the J2EE™ Application Client 58

Running the Web Client 59

Modifying the J2EE™ Application 59

Modifying a Class File 59

Adding a File 60

Modifying the Web Client 60

Modifying a Deployment Setting 60

Common Problems and Their Solutions 61

Cannot Start the J2EE Server 61

Naming and Directory Service Port Conflict 61

Web Service Port Conflict 61

Compilation Errors 61

Ant Cannot Locate the Build File 61

The Compiler Cannot Resolve Symbols 62

J2EE Application Client Runtime Errors 62

The Client Cannot Find ConverterApp.ear 62

The Client Cannot Find the ConverterClient Component 62

The Login Failed 63

The J2EE Application Has Not Been Deployed 63

The JNDI Name is Incorrect 63

Web Client Runtime Errors 63

The Web Context in the URL is Incorrect 63

The J2EE Application Has Not Been Deployed 63

The JNDI Name is Incorrect 64

Deployment Errors 64

Trang 6

Chapter 3: Session Beans 65

A Session Bean Example 66

Session Bean Class 66

TheSessionBean Interface 68

TheejbCreate Methods .68

Business Methods 69

Home Interface 70

Remote Interface .71

Helper Classes 72

State Management Modes 72

Stateful Session Beans 72

Stateless Session Beans 73

Choosing Between Stateful and Stateless Session Beans 73

The Life Cycle of a Session Bean 74

The Stateful Session Bean Life Cycle 74

The Stateless Session Bean Life Cycle 75

Other Enterprise Bean Features 76

Accessing Environment Entries 76

Comparing Enterprise Beans 77

Passing an Enterprise Bean’s Object Reference 78

Chapter 4: Entity Beans .81

Characteristics of Entity Beans 82

Persistence 82

Bean-Managed Persistence 82

Container-Managed Persistence 82

Shared Access 83

Primary Key 83

Trang 7

A Bean-Managed Persistence Example 83

Entity Bean Class 84

The EntityBean Interface 84

TheejbCreate Method 85

TheejbPostCreate Method 86

TheejbRemove Method 87

TheejbLoad andejbStore Methods 87

The Finder Methods 88

The Business Methods 90

Database Calls 92

Home Interface 92

Remote Interface 94

Tips for Running theAccountEJB Example 94

Setting Up the Database 94

Running the New Enterprise Bean Wizard 95

Deploying the J2EE Application 95

Running the J2EE Application 96

Mapping Table Relationships For Bean-Managed Persistence 96

One-to-One Relationships 97

Tips for Running theStorageBinEJB Example 99

One-to-Many Relationships 100

A Helper Class for the Child Table 101

Tips for Running theOrderEJB Example: 104

An Entity Bean for the Child Table 104

Tips for Running theSalesRepEJB Example: 107

Many-to-Many Relationships 108

Tips for running theEnrollerEJB example: 110

About Container-Managed Persistence 111

A Container-Managed Persistence Example 111

Primary Key Class 111

Creating a Primary Key Class 112

Class Requirements 113

Bean-Managed Persistence and the Primary Key Class 113

Container-Managed Persistence and the Primary Key Class 114

Getting the Primary Key 114

Handling Exceptions 115

The Life Cycle of an Entity Bean 116

Chapter 5: Web Components 119

Web Component Life Cycle 120

Trang 8

Packaging Web Components 122

Creating a WAR .122

Adding a WAR to a J2EE Application 123

Adding a Web Component to a WAR 123

Configuring Web Components 124

Application-Level Configuration .125

Context Root 125

WAR-Level Configuration 125

Context Parameters 125

References to Environment Entries, Enterprise Beans, Resource En-vironment Entries, or Resources .126

Event Listeners 126

Error Mapping .126

Filter Mapping 127

Component-Level Configuration 128

Initialization Parameters 128

Specifying an Alias Path .128

Deploying Web Components 129

Executing Web Components .129

Updating Web Components 129

Chapter 6: Java Servlet Technology 133

What is a Servlet? 134

The Example Servlets 135

Troubleshooting 138

Servlet Life Cycle 139

Monitoring Servlet Life Cycle Events 140

Defining The Listener Class 140

Specifying Event Listener Classes 141

Handling Errors 142

Sharing Information 142

Scope Objects .142

Controlling Concurrent Access to Shared Resources 143

Initializing a Servlet 145

Writing Service Methods 145

Getting Information From Requests 146

Constructing Responses 148

Filtering Requests and Responses 151

Defining the Filter Class 152

Specifying Filter Mappings 155

Trang 9

Invoking Other Web Resources 156

Including the Content of Another Resource in the Response 157

Transferring a Control to Another Web Component 158

Accessing the Web Context 159

Maintaining Client State 160

Accessing a Session 160

Associating Attributes with a Session 161

Notifying Objects That Are Added To a Session 161

Session Management 162

Session Tracking 162

Finalizing a Servlet 163

Tracking Service Requests 164

Providing a Clean Shutdown 165

Creating Polite Long-Running Methods 166

Chapter 7: JavaServer Pages™ Technology 167

What is a JSP Page? 168

The Example JSP Pages 171

The Life Cycle of a JSP Page 173

Translation and Compilation 174

Execution 175

Buffering 175

Handling Errors 175

Initializing and Finalizing a JSP Page 176

Creating Static Content 178

Creating Dynamic Content 179

Using Objects Within JSP Pages 179

Implicit Objects 179

Application-Specific Objects 180

Shared Objects 181

JSP Scripting Elements 181

Declarations 182

Scriptlets 182

Expressions 184

Including Content in a JSP Page 185

Transferring Control to Another Web Component 186

Param Element 186

Including an Applet 186

Extending the JSP Language 189

Trang 10

Chapter 8: JavaBeans™ Components in JSP™ Pages 191

JavaBeans Component Design Conventions .192

Why Use a JavaBeans Component? 193

Creating and Using a JavaBeans Component 194

Setting JavaBeans Component Properties .194

Retrieving JavaBeans Component Properties 197

Chapter 9: Custom Tags in JSP™ Pages 199

What is a Custom Tag? 200

The Example Tags .200

Using Tags 204

Declaring Tag Libraries 204

Types of Tags .205

Simple Tags 205

Tags With Attributes .205

Tags With Bodies 207

Choosing Between Passing Information as Attributes or Body 207 Tags That Define Scripting Variables 207

Cooperating Tags 208

Defining Tags 208

Tag Handlers 209

Tag Library Descriptors 210

Listener Element 211

Tag Element 211

Simple Tags 212

Tag Handlers .212

Body-content Element 213

Tags With Attributes 213

Defining Attributes in a Tag Handler 213

Attribute Element 214

Attribute Validation 215

Tags With Bodies .216

Tag Handlers .216

Body-content Element 218

Tags That Define Scripting Variables 218

Tag Handlers .218

Providing Information About the Scripting Variable 219

Cooperating Tags 222

Trang 11

Examples 224

An Iteration Tag 224

JSP Page 224

Tag Handler 225

Tag Extra Info Class 227

A Template Tag Library 227

JSP Page 228

Tag Handlers 229

How Is a Tag Handler Invoked? 233

Chapter 10: Transactions 235

What is a Transaction? 236

Container-Managed Transactions 236

Transaction Attributes 237

Transaction Attribute Values 238

Required 238

RequiresNew 238

Mandatory 238

NotSupported 239

Supports 239

Never 239

Summary of Transaction Attributes 239

Setting Transaction Attributes 240

Rolling Back a Container-Managed Transaction 241

Synchronizing a Session Bean’s Instance Variables 242

Methods Not Allowed in Container-Managed Transactions 243

Bean-Managed Transactions 243

JDBC Transactions 244

JTA Transactions 245

Returning Without Committing 246

Methods Not Allowed in Bean-Managed Transactions 247

Summary of Transaction Options 247

Transaction Timeouts 248

Isolation Levels 249

Updating Multiple Databases 250

Trang 12

Chapter 11: Security 253

Authentication 254

J2EE Users, Realms, and Groups 255

Managing J2EE Users and Groups 256

Authentication Mechanisms .257

Web-Tier Authentication 257

Configuring A Web Component’s Authentication Mechanism 258 Using Hybrid Authentication to Enhance Confidentiality 258

Controlling Access to J2EE Resources 259

Controlling Access to Web Resources 259

Controlling Access to Enterprise Beans 259

Unprotected Resources 260

Client Authentication 260

Auto-Registration of Users 261

Web Client Authentication 261

Data Protection 261

Developing a Custom Web Tier User Authentication Interface .261 Application Client Authentication 261

Setting Component Security Identities 262

Capturing a Security Context (Servlet) .262

Container Authentication 262

Setting Up a Server Certificate 262

Configuring EJB Target Security Requirements 263

Configuring Resource Signon (Connectors) 264

Authorization .264

Declaring Roles 265

Declaring Method Permissions 265

Declaring Role References .266

Mapping Roles to J2EE Users and Groups 266

Linking Role References to Roles 267

Configuring J2SE Security Policy Files 267

Determining the Caller Identity 267

Making Portable Access Decisions Programmatically from Components 267 Protecting Messages 268

Application Scenarios 268

J2EE Application Client 268

Web Browser Client .268

Trang 13

Chapter 12: Resource Connections 269

JNDI Names and Resource References 270

Definitions 270

Specifying a Resource Reference 270

Mapping a Resource Reference to a JNDI Name 271

Database Connections for Enterprise Beans 271

Coded Connections 271

How to Connect 271

When To Connect 272

Specifying Database Users and Passwords 273

Container-Managed Connections 273

Connection Pooling 273

Mail Session Connections 274

Tips for Running the ConfirmerEJB Example 275

URL Connections 276

Tips for Running the HTMLReaderEJB Example 277

Chapter 13: J2EE™Connector Technology 281

About Resource Adapters 282

Resource Adapter Contracts 282

Administering Resource Adapters 283

The Black Box Resource Adapters 285

Transaction Levels 285

Properties 286

Configuring JDBC™ Drivers 287

The Non-XA Black Box Adapters 287

The XA Black Box Adapters 287

Resource Adapter Tutorial 288

Setting Up 288

Deploying the Resource Adapter 288

Testing the Resource Adapter 289

Trang 14

Common Client Interface (CCI) 291

Overview of the CCI 291

Programming with the CCI 293

Database Stored Procedures 295

Mapping to Stored Procedure Parameters 296

Reading Database Records 298

Inserting Database Records 300

Writing a CCI Client 302

CCI Tutorial 302

Deploy the Resource Adapter 302

Set Up the Database 303

Create the J2EE Application .304

Test the Resource Adapter 306

Chapter 14: HTTP Overview 307

HTTP Requests 307

HTTP Responses 308

Chapter 15: J2EESDK Tools 309

J2EE Administration Tool .310

Cleanup Tool 311

Cloudscape Server .311

Starting and Stopping Cloudscape 311

Cloudscape Server Configuration 312

Cloudscapeij Tool .312

Deployment Tool 313

J2EE Server 314

Key Tool 314

Trang 15

Packager 315

EJB JAR File 315

Syntax 315

Example 315

Web Application WAR File 316

Syntax 316

Example: Creating a Simple WAR File 316

Example: Specifying Individual Content Files 316

Example: Specifying Servlets and JSP Files 316

Application Client JAR File 317

Syntax 317

Example 317

J2EE Application EAR File 317

Syntax 317

Example: Creating an EAR File 318

Example: Specifying the Runtime Deployment Descriptor 318

Resource Adapter RAR File 319

Syntax 319

Realm Tool 319

Runclient Script 320

Verifier 320

Command-Line Verifier 320

Stand-Alone GUI Verifier 321

Glossary 323

Trang 17

Preface

THEJava Tutorial has been an indispensable resource for many programmerslearning the Java programming language This tutorial hopes to serve the samerole for developers encountering the Java™ 2 Platform, Enterprise Edition(J2EE™) for the first time It follows an example-oriented focus similar to theJava Tutorial

Who Should Use This Tutorial xviiAbout the Examples xviii

Related Information xxHow to Print This Tutorial xxiTypographical Conventions xxiAcknowledgments xxii

Who Should Use This Tutorial

This tutorial is intended for programmers interested in developing and deployingJ2EE applications It covers the main component technologies comprising theJ2EE platform and describes how to develop J2EE components and deploy them

on the J2EE SDK

This tutorial is not intended for J2EE server or tools vendors It does not explainhow to implement the J2EE architecture, nor does it explain the internals of theJ2EE SDK The J2EE specifications describe the J2EE architecture and can bedownloaded from:

http://java.sun.com/j2ee/docs.html#specs

Trang 18

About the Examples

This tutorial includes many complete, working examples

Prerequisites for the Examples

To understand the examples you will need a good knowledge of the Java gramming language, SQL, and relational database concepts The following top-ics in the Java Tutorial are particularly relevant:

pro-Where to Find the Examples

If you are viewing this online, and you want to build and run the examples, youneed to download the tutorial bundle from:

http://java.sun.com/j2ee/download.html#tutorial

Once you have installed the bundle, the example code is in theexamples/src

directory, with subdirectoriesejbfor enterprise bean technology examples,web

for web technology examples, andconnector for connector technology ples

exam-How to Build and Run the Examples

This tutorial documents the J2EE SDK version 1.3 To build, deploy, and run theexamples you need a copy of the J2EE SDK 1.3 and the J2SE™ SDK 1.3, alsoknown as a JDK You can download the J2EE SDK from:

Trang 19

and the J2SE 1.3 from:

http://java.sun.com/j2se/1.3/

The examples are distributed with a configuration file forantversion 1.2 A table make tool, ant is hosted by the Jakarta project at the Apache SoftwareFoundation You can downloadant from:

por-http://jakarta.apache.org/builds/jakarta-ant/release/v1.2/bin

To build the examples:

1 Download and install the J2SE SDK 1.3, J2EE SDK 1.3, andant

2 The installation instructions for the J2SE SDK, J2EE SDK, and ant

explain how to set the required environment variables Verify that the ronment variables have been set to the values noted in the following table

envi-3 Go to theexamples/src directory

4 Open the filebuild.xml in a text editor Edit the line:

<property name="j2ee-home" value="C:\j2sdkee1.3" />

and set the value of thej2ee-homeproperty to be the J2EE SDK tion directory

installa-5 Executeant target For example, to build all the examples, executeant allor to build the web layer examples, executeant web The build processdeposits the output into the directoryexamples/build

Environment Variable Value

JAVA_HOME The location of the J2SE SDK installation.

J2EE_HOME The location of the J2EE SDK installation.

ANT_HOME The location of the ant installation.

PATH Should include thebin directory of the J2EE SDK and ant

installation.

Trang 20

Related Information

This tutorial provides a concise overview of how to use the central componenttechnologies in the J2EE platform For more information about these technolo-gies, see:

The J2EE platform includes a wide variety of APIs that this tutorial only brieflytouches on Some of these technologies have their own tutorials:

For complete information on these topics see:

Component Technology Web Site

Enterprise JavaBeans™ (EJB™) http://java.sun.com/products/ejb

Java Servlet http://java.sun.com/products/servlets

JavaServer Pages™ (JSP™) http://java.sun.com/products/jsp

Java Message Service (JMS) http://java.sun.com/products/jms/tutorial/

Java Naming and DirectoryInterface™ (JNDI) http://java.sun.com/products/jndi/tutorial/

Extensible Markup Language(XML) http://java.sun.com/xml/tutorial_intro.html

J2EE Connector http://java.sun.com/j2ee/connector

Trang 21

Once you have become familiar with the J2EE technologies described in thistutorial, you may be interested in guidelines for architecting J2EE applications.

The J2EE Blueprints is a book and sample application that illustrate best tices for developing and deploying J2EE applications You can obtain the J2EEBlueprints from:

prac-http://java.sun.com/j2ee/blueprints

How to Print This Tutorial

To print this tutorial, follow these steps:

• Ensure that Adobe Acrobat Reader is installed on your system

• Using your browser, access the PDF version of this book

• Click the printer icon in Adobe Acrobat Reader

monospace URLs, code examples, file names, command

names, programming language keywords

italic monospace Programming variables, variable file names

Trang 23

To reduce costs and fast-track enterprise application design and development,the Java™ 2 Platform, Enterprise Edition (J2EE™) technology provides a com-ponent-based approach to the design, development, assembly, and deployment ofenterprise applications The J2EE platform gives you a multitiered distributedapplication model, the ability to reuse components, a unified security model, andflexible transaction control Not only can you deliver innovative customer solu-tions to market faster than ever, but your platform-independent J2EE compo-nent-based solutions are not tied to the products and APIs of any one vendor.This tutorial takes an examples-based approach to describing the features andfunctionalities available in J2EE SDK version 1.3 Whether you are a new or anexperienced enterprise developer, you should find the examples and accompany-ing text a valuable and accessible knowledge base for creating your own enter-prise solutions.

If you are new to J2EE applications development, this chapter is a good place tostart Here you will learn the J2EE architecture, become acquainted with impor-tant terms and concepts, and find out how to approach J2EE applications pro-gramming, assembly, and deployment

Trang 24

Distributed Multitiered Applications 24J2EE Application Components 25Client Components 26

Thin Clients 28Web Components 28Business Components 29Enterprise Information System Tier 30J2EE Architecture 30

Containers and Services 30Container Types 32Packaging 33

Development Roles 34J2EE Product Provider 34Tool Provider 34

Application Component Provider 35Application Assembler 35

Application Deployer and Administrator 36Reference Implementation Software 36

Web Server 37Database Access 37J2EE APIs 37Tools 40

Distributed Multitiered Applications

The J2EE platform uses a multitiered distributed application model This meansapplication logic is divided into components according to function, and the vari-ous application components that make up a J2EE application are installed on dif-ferent machines depending on which tier in the multitiered J2EE environmentthe application component belongs Figure 1 shows two multitiered J2EE appli-cations divided into the tiers described in the bullet list below The J2EE applica-tion parts shown in Figure 1 are presented in J2EE ApplicationComponents (page 25)

• Client tier components run on the client machine

• Web tier components run on the J2EE server

• Business tier components run on the J2EE server

• Enterprise information system (EIS) tier software runs on the EIS serverWhile a J2EE application can consist of the three or four tiers shown in Figure 1,J2EE multitiered applications are generally considered to be three-tiered appli-cations because they are distributed over three different locations: client

Trang 25

machines, J2EE server machine, and the database or legacy machines at theback-end Three-tiered applications that run in this way extend the standard two-tiered client and server model by placing a multithreaded application serverbetween the client application and back-end storage.

Figure 1 Multitiered Applications

J2EE Application Components

J2EE applications are made up of components A J2EE component is a tained functional software unit that is assembled into a J2EE application with itsrelated classes and files and communicates with other components The J2EEspecification defines the following J2EE components:

self-con-• Application clients and applets are client components

• Java Servlet and JavaServer Pages™ (JSP™) technology components areweb components

• Enterprise JavaBeans™ (EJB™) components (enterprise beans) are ness components

busi-J2EE components are written in the Java programming language and compiled

in the same way as any Java programming language program The differencewhen you work with the J2EE platform, is J2EE components are assembled into

Application Client

Enterprise Beans

Dynamic HTML pages

JSP pages

Enterprise Beans

Database

Client tier

Web tier

Business tier

EIS tier

Client Machine

J2EE Server Machine

Database Server Machine

Database

J2EE Application 1

J2EE Application 2

Trang 26

a J2EE application, verified that they are well-formed and in compliance withthe J2EE specification, and deployed to production where they are run and man-aged by the J2EE server.

Client Components

A J2EE application can be web-based or non-web-based An application clientexecutes on the client machine for a non-web-based J2EE application, and a webbrowser downloads web pages and applets to the client machine for a web-basedJ2EE application

Application Clients

An application client runs on a client machine and provides a way for users tohandle tasks such as J2EE system or application administration It typically has agraphical user interface created from Project Swing or Abstract Window Toolkit(AWT) APIs, but a command-line interface is certainly possible

Application clients directly access enterprise beans running in the business tier.However, if the J2EE application client requirements warrant it, an applicationclient can open an HTTP connection to establish communication with a servletrunning in the web tier

Web Browsers

The user’s web browser downloads static or dynamic Hypertext Markup guage (HTML), Wireless Markup Language (WML), or Extensible MarkupLanguage (XML) web pages from the web tier Dynamic web pages are gener-ated by servlets or pages created with JavaServer Pages technology (JSP pages)running in the web tier

Lan-Applets

A web page downloaded from the web tier can include an embedded applet Anapplet is a small client application written in the Java programming languagethat executes in the Java VM installed in the web browser However, client sys-tems will likely need Java Plug-in and possibly a security policy file so the appletcan successfully execute in the web browser

JSP pages are the preferred API for creating a web-based client program because

no plug-ins or security policy files are needed on the client systems Also, JSPpages enable cleaner and more modular application design because they provide

a way to separate applications programming from web page design This means

Trang 27

personnel involved in web page design do not need to understand Java ming language syntax to do their jobs.

program-Applets that run in other network-based systems such as handheld devices or carphones can render Wireless Markup Language (WML) pages generated by a JSPpage or servlet running on the J2EE server The WML page is delivered overWireless Application Protocol (WAP) and the network configuration requires agateway to translate WAP to HTTP and back again The gateway translates theWAP request coming from the handheld device to an HTTP request for the J2EEserver, and then translates the HTTP server response and WML page to a WAPserver response and WML page for display on the handheld device

JavaBeans™ Component Architecture

The client tier might also include a component based on the JavaBeans™ ponent architecture (JavaBeans component) to manage the data flow between anapplication client or applet and components running on the J2EE server Java-Beans components are not considered J2EE components by the J2EE specifica-tion

com-JavaBeans components written for the J2EE platform have instance variablesandgetandsetmethods for accessing the data in the instance variables Java-Beans components used in this way are typically simple in design and imple-mentation, but should conform to the naming and design conventions outlined inthe JavaBeans component architecture

J2EE Server Communications

Figure 2 shows the various elements that can make up the client tier The clientcommunicates with the business tier running on the J2EE server either directly,

or as in the case of a client running in a browser, by going through JSP pages orservlets running in the web tier

Trang 28

Figure 2 Server Communications

Thin Clients

J2EE applications use a thin client A thin client is a lightweight interface to theapplication that does not do things like query databases, execute complex busi-ness rules, or connect to legacy applications Heavyweight operations like theseare off-loaded to web or enterprise beans executing on the J2EE server wherethey can leverage the security, speed, services, and reliability of J2EE server-sidetechnologies

Web Components

J2EE web components can be either JSP pages or servlets Servlets are Java gramming language classes that dynamically process requests and constructresponses JSP pages are text-based documents that execute as servlets, but allow

pro-a more npro-aturpro-al pro-appropro-ach to crepro-ating stpro-atic content

Static HTML pages and applets are bundled with web components during cation assembly, but are not considered web components by the J2EE specifica-tion Server-side utility classes can also be bundled with web components, andlike HTML pages, are not considered web components

appli-Like the client tier and as shown in Figure 3, the web tier might include a Beans object to manage the user input and send that input to enterprise beansrunning in the business tier for processing

Java-Web Browser Web pages, applets, and optional JavaBeans class

Application Client and optional JavaBeans class

Client Tier

Web Tier

Business Tier

J2EE Server

Trang 29

Figure 3 Web Tier and J2EE Application

Business Components

Business code, which is logic that solves or meets the needs of a particular ness domain such as banking, retail, or finance, is handled by enterprise beansrunning in the business tier Figure 4 shows how an enterprise bean receives datafrom client programs, processes it (if necessary), and sends it to the enterpriseinformation system tier for storage An enterprise bean also retrieves data fromstorage, processes it (if necessary), and sends it back to the client program

busi-There are three kinds of enterprise beans: session beans, entity beans, and sage-driven beans A session bean represents a transient conversation with a cli-ent When the client finishes executing, the session bean and its data are gone Incontrast, an entity bean represents persistent data stored in one row of a databasetable If the client terminates or if the server shuts down, the underlying servicesensure the entity bean data is saved

mes-A message-driven bean combines features of a session bean and a Java MessageService (JMS) message listener, allowing a business component to receive JMSmessages asynchronously This tutorial describes entity beans and session beans

For information on message-driven beans, see the Java Message Service rial, which is online at:

Tuto-http://java.sun.com/products/jms/tutorial/index.html

Web Browser

Web pages, applet, and optional JavaBeans class

Application Client and optional JavaBeans class

JavaBeans Class (optional)

Trang 30

Figure 4 Business and EIS Tiers

Enterprise Information System Tier

The enterprise information system tier handles enterprise information systemsoftware, and includes enterprise infrastructure systems such as enterpriseresource planning (ERP), mainframe transaction processing, database systems,and other legacy information systems J2EE application components might needaccess to enterprise information systems for database connectivity, for example

J2EE Architecture

Normally, thin-client multitiered applications are hard to write because theyinvolve many lines of intricate code to handle transaction and state management,multithreading, resource pooling, and other complex low-level details The com-ponent-based and platform-independent J2EE architecture makes J2EE applica-tions easy to write because business logic is organized into reusable componentsand the J2EE server provides underlying services in the form of a container forevery component type Because you do not have to develop these services your-self, you are free to concentrate on solving the business problem at hand

Containers and Services

Component are installed in their containers during deployment and are the face between a component and the low-level platform-specific functionality thatsupports the component Before a web, enterprise bean, or application client

inter-Web Browser Web pages, applets, and optional JavaBeans class

Application Client and optional JavaBeans class

JavaBeans Class (optional)

JSP Pages Servlets

Entity Beans Session Beans Message-Driven Beans

Business Tier

Database

& Legacy Systems

EIS Tier

J2EE Server

Trang 31

component can be executed, it must be assembled into a J2EE application anddeployed into its container.

The assembly process involves specifying container settings for each component

in the J2EE application and for the J2EE application itself Container settingscustomize the underlying support provided by the J2EE Server, which includeservices such as security, transaction management, Java Naming and DirectoryInterface™ (JNDI) lookups, and remote connectivity Here are some of the high-lights:

• The J2EE security model lets you configure a web component or enterprisebean so system resources are accessed only by authorized users

• The J2EE transaction model lets you specify relationships among methodsthat make up a single transaction so all methods in one transaction aretreated as a single unit

• JNDI lookup services provide a unified interface to multiple naming anddirectory services in the enterprise so application components can accessnaming and directory services

• The J2EE remote connectivity model manages low-level communicationsbetween clients and enterprise beans After an enterprise bean is created, aclient invokes methods on it as if it were in the same virtual machine

The fact that the J2EE architecture provides configurable services means thatapplication components within the same J2EE application can behave differentlybased on where they are deployed For example, an enterprise bean can havesecurity settings that allow it a certain level of access to database data in one pro-duction environment and another level of database access in another productionenvironment

The container also manages non-configurable services such as enterprise beanand servlet life cycles, database connection resource pooling, data persistence,and access to the J2EE platform APIs described in J2EE APIs (page 37)

Although data persistence is a non-configurable service, the J2EE architecturelets you override container-managed persistence by including the appropriatecode in your enterprise bean implementation when you want more control thanthe default container-managed persistence provides For example, you might usebean-managed persistence to implement your own finder (search) methods or tocreate a customized database cache

Trang 32

Container Types

The deployment process installs J2EE application components in the followingtypes of J2EE containers The J2EE components and container addressed in thistutorial are shown in Figure 5

• An Enterprise JavaBeans (EJB) container manages the execution of allenterprise beans for one J2EE application Enterprise beans and their con-tainer run on the J2EE server

• A web container manages the execution of all JSP page and servlet ponents for one J2EE application Web components and their container run

com-on the J2EE server

• An application client container manages the execution of all applicationclient components for one J2EE application Application clients and theircontainer run on the client machine

• An applet container is the web browser and Java Plug-in combination ning on the client machine

run-Figure 5 J2EE Server and Containers

J2EE Server

Database

EJB Container

Enterprise Bean

Enterprise Bean

Web Container

JSP Page Servlet

Application Client Container

Application Client

Client Machine

Browser

Trang 33

J2EE components are packaged separately and bundled into a J2EE applicationfor deployment Each component, its related files such as GIF and HTML files orserver-side utility classes, and a deployment descriptor (DD), are assembled into

a module and added to the J2EE application A J2EE application is composed ofone or more enterprise bean, web, or application client component modules Thefinal enterprise solution can use one J2EE application or be made up of two ormore J2EE applications depending on design requirements

A J2EE application and each of its modules has its own deployment descriptor

A deployment descriptor is an Extensible Markup Language (XML) text-basedfile with an .xml extension that describes a component’s deployment settings

An enterprise bean module deployment descriptor, for example, declares action attributes and security authorizations for an enterprise bean Becausedeployment descriptor information is declarative, it can be changed withoutmodifying the bean source code At run time, the J2EE server reads the deploy-ment descriptor and acts upon the component accordingly

trans-A J2EE application with all of its modules is delivered in an Enterprise trans-ARchive(EAR) file An EAR file is a standard JAR file with an .earextension In theGUI version of the J2EE SDK application deployment tool, you create an EARfile first and add JAR and WAR files to the EAR If you use the command linepackager tools, however, you create the Java ARchive (JARs) and Web ARchive(WAR) files first and create the EAR The J2EE SDK tools are described inTools (page 40)

• Each EJB JAR file contains its deployment descriptor, related files, and the

.class files for the enterprise bean

• Each application client JAR file contains its deployment descriptor, relatedfiles, and the.class files for the application client

• Each WAR file contains its deployment descriptor, related files, and the

.class files for the servlet or.jsp files for a JSP page

Using modules and EAR files makes it possible to assemble a number of ent J2EE applications using some of the same components No extra coding isneeded; it is just a matter of assembling various J2EE modules into J2EE EARfiles

Trang 34

differ-Development Roles

Reusable modules make it possible to divide the application development anddeployment process into distinct roles so different people or companies can per-form different parts of the process

The first two roles involve purchasing and installing the J2EE product and tools.Once software is purchased and installed, J2EE components can be developed byapplication component providers, assembled by application assemblers, anddeployed by application deployers In a large organization, each of these rolesmight be executed by different individuals or teams This division of labor worksbecause each of the earlier roles outputs a portable file that is the input for a sub-sequent role For example, in the application component development phase, anenterprise bean software developer delivers EJB JAR files In the applicationassembly role, another developer combines these EJB JAR files into a J2EEapplication and saves it in an EAR file In the application deployment role, a sys-tem administrator at the customer site uses the EAR file to install the J2EE appli-cation into a J2EE server

The different roles are not always executed by different people If you work for asmall company, for example, or if you are prototyping a sample application, youmight perform the tasks in every phase

J2EE Product Provider

The J2EE product provider is the company that designs and makes available forpurchase the J2EE platform, APIs, and other features defined in the J2EE speci-fication Product providers are typically operating system, database system,application server, or web server vendors who implement the J2EE platformaccording to the Java 2 Platform, Enterprise Edition Specification

Tool Provider

The tool provider is the person or company who makes development, assembly,and packaging tools used by component providers, assemblers, and deployers.See Tools (page 40) for information on the tools available with J2EE SDK ver-sion 1.3

Trang 35

Application Component Provider

The application component provider is the company or person who creates webcomponents, enterprise beans, applets, or application clients for use in J2EEapplications

Enterprise Bean Creation

A software developer performs the following tasks to deliver an EJB JAR filethat contains the enterprise bean:

• Writes and compiles the source code

• Specifies the deployment descriptor

• Bundles the.class files and deployment descriptor into an EJB JAR file

Web Component Creation

A web designer (JSP pages) or software developer (servlets) performs the lowing tasks to deliver a WAR file containing the web component

fol-• Writes and compiles servlet source code

• Writes JSP and HTML files

• Specifies the deployment descriptor for the web component

• Bundles the.class,.jsp,.html, and deployment descriptor files in theWAR file

J2EE Application Client Creation

A software developer performs the following tasks to deliver a JAR file ing the J2EE application client

contain-• Writes and compiles the source code

• Specifies the deployment descriptor for the client

• Bundles the.class files and deployment descriptor into the JAR file

Application Assembler

The application assembler is the company or person who gets application ponent JAR files from component providers and assembles them into a J2EEapplication EAR file The assembler or deployer can edit the deploymentdescriptor directly or use tools that correctly add XML tags according to interac-

Trang 36

com-tive selections A software developer performs the following tasks to deliver anEAR file containing the J2EE application.

• Assembles EJB JAR and web components (WAR) files created in the vious phases into a J2EE application (EAR) file

pre-• Specifies the deployment descriptor for the J2EE application

• Verifies that the contents of the EAR file are well-formed and comply withthe J2EE specification

Application Deployer and Administrator

The company or person who configures and deploys the J2EE application,administers the computing and networking infrastructure where J2EE applica-tions run, and oversees the runtime environment Duties include such things assetting transaction controls, security attributes, and specifying connections todatabases

During configuration, the deployer follows instructions supplied by the tion component provider to resolve external dependencies, specify security set-tings, and assign transaction attributes During installation, the deployer movesthe application components to the server, and generates the container-specificclasses and interfaces

applica-A deployer/system administrator performs the following tasks to install and figure a J2EE application

con-• Adds the J2EE application (EAR) file created in the preceding phase to theJ2EE server

• Configures the J2EE application for the operational environment by ifying the deployment descriptor of the J2EE application

mod-• Verifies that the contents of the EAR file are well-formed and comply withthe J2EE specification

• Deploys (installs) the J2EE application EAR file into the J2EE server

Reference Implementation Software

The J2EE SDK is a non-commercial operational definition of the J2EE platformand specification made freely available by Sun Microsystems for demonstra-tions, prototyping, and educational uses It comes with the J2EE application

Trang 37

server, web server, relational database, J2EE APIs, and complete set of ment and deployment tools You can download the J2EE SDK from the web:

develop-http://java.sun.com/j2ee/download.html#sdk

• Product providers use the J2EE SDK to determine what their tions must do under a given set of application conditions, and to run theJ2EE Compatibility Test Suite to test that their J2EE products fully complywith the specification

implementa-• Application component developers run their J2EE applications on theJ2EE SDK to verify the applications are fully portable across all J2EEproducts and tools

Web Server

The web server provides services to one or more web containers For example, aweb container typically relies on a web server to provide HTTP message han-dling A J2EE implementation is not required to support a particular type of webserver, which means the web server supported by different J2EE products canvary

Database Access

The relational database provides persistent storage for application data A J2EEimplementation is not required to support a particular type of database whichmeans the database supported by different J2EE products can vary See theRelease Notes included with the J2EE SDK download for a list of the databasescurrently supported by the reference implementation

J2EE APIs

The Java 2 Platform, Standard Edition (J2SE™)SDK is required to run the J2EESDK and provides core APIs for writing J2EE components, core developmenttools, and the Java virtual machine The J2EE SDK provides the following APIs

to be used in J2EE applications

Enterprise JavaBeans Technology 2.0

An enterprise bean is a body of code with fields and methods to implement ules of business logic You can think of an enterprise bean as a building block

Trang 38

mod-that can be used alone or with other enterprise beans to execute business logic onthe J2EE server.

There are three kinds of enterprise beans: session beans, entity beans, and sage-driven beans as described in Business Components (page 29) You do nothave to write any SQL code or use the JDBC™ API directly to perform databaseaccess operations with an entity bean The EJB container handles this for you.However, if you override the default container-managed persistence for any rea-son, you will need to use the JDBC API Also, if you choose to have a sessionbean access the database, you have to use the JDBC API

mes-JDBC™ 2.0 API

The JDBC API lets you invoke SQL commands from Java programing languagemethods You use the JDBC API in an enterprise bean when you override thedefault container-managed persistence or have a session bean access the data-base With container-managed persistence, database access operations are han-dled by the container and your enterprise bean implementation contains noJDBC code or SQL commands You can also use the JDBC API from a servlet orJSP page to access the database directly without going through an enterprisebean

The JDBC API has two parts: an application-level interface used by the tion components to access a database, and a service provider interface to attach aJDBC driver to the J2EE platform

applica-Java Servlet Technology 2.3

Java Servlet technology lets you define HTTP-specific servlet classes A servletclass extends the capabilities of servers that host applications accessed by way of

a request-response programming model Although servlets can respond to anytype of request, they are commonly used to extend the applications hosted byweb servers

JavaServer Pages (JSP) Technology 1.2

JSP pages technology lets you put snippets of servlet code directly into a based document A JSP page is a text-based document that contains two types oftext: static template data which can be expressed in any text-based format such

text-as HTML, WML, and XML, and JSP elements that determine how the page structs dynamic content

Trang 39

con-Java Message Service (JMS) 1.0

The JMS API is a messaging standard that allows J2EE application components

to create, send, receive, and read messages It enables distributed communicationthat is loosely coupled, reliable, and asynchronous For more information onJMSsee theonline Java Message Service Tutorial:

http://java.sun.com/products/jms/tutorial/index.html

Java Transaction API (JTA) 1.0

The JTA API provides a standard demarcation interface for demarcating tions The J2EE architecture provides a default auto commit to handle transac-tion commits and roll backs An auto commit means any other applicationsviewing data will see the updated data after each database read or write opera-tion However, if your application performs two separate database access opera-tions that depend on each other, you will want to use the JTA API to demarcatewhere the entire transaction including both operations begins, rolls back, andcommits

transac-JavaMail™ Technology 1.2

Many Internet applications need to send email notifications so the J2EE platformincludes the JavaMail API with a JavaMail service provider that applicationcomponents can use to send Internet mail The JavaMail API has two parts: anapplication-level interface used by the application components to send mail, and

a service provider interface

JavaBeans Activation Framework 1.0

The JavaBeans Activation Framework is included because JavaMail uses it Itprovides standard services to determine the type of an arbitrary piece of data,encapsulate access to it, discover the operations available on it, and create theappropriate JavaBean component to perform those operations

Java API for XML (JAXP) 1.1

XML is a language for representing and describing text-based data so the datacan be read and handled by any program or tool that uses XML APIs Programsand tools can generate XML files that other programs and tools can read andhandle

For example, a J2EE application can use XML to produce reports, and differentcompanies that receive the reports can handle the data in a way that best suitstheir needs One company might put the XML data through a program to trans-

Trang 40

late the XML to HTML so it can post the reports to the web, another companymight put the XML data through a tool to create a marketing presentation, andyet another company might read the XML data into its J2EE application for pro-cessing.

J2EE Connector API 1.0

The Connector API is used by J2EE tools vendors and system integrators to ate resource adapters that support access to enterprise information systems thatcan be plugged into any J2EE product A resource adapter is a software compo-nent that allows J2EE application components to access and interact with theunderlying resource manager Because a resource adapter is specific to itsresource manager, there is typically a different resource adapter for each type ofdatabase or EIS

cre-Java Authentication and Authorization Service (JAAS) 1.0

The Java Authentication and Authorization Service (JAAS) provides a way for aJ2EE application to authenticate and authorize a specific user or group of users

to run it

JAAS is a Java programing language version of the standard Pluggable cation Module (PAM) framework that extends the Java 2 platform security archi-tecture to support user-based authorization

Authenti-Tools

The J2EE reference implementation provides an application deployment tooland an array of scripts for assembling, verifying, and deploying J2EE applica-tions and managing your development and production environments SeeJ2EE™SDK Tools (page 309) for a discussion of the tools

Application Deployment Tool

The J2EE reference implementation provides an application deployment tool forassembling, verifying, and deploying J2EE applications It comes in two ver-sions: command-line and GUI

Ngày đăng: 27/06/2014, 08:20

w