• Nenhum resultado encontrado

The Java EE 5 Tutorial

N/A
N/A
Protected

Academic year: 2019

Share "The Java EE 5 Tutorial"

Copied!
1124
0
0

Texto

(1)

The Java EE 5 Tutorial

For Sun Java System Application Server 9.1

Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054 U.S.A.

(2)

Copyright 2007 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more U.S. patents or pending patent applications in the U.S. and in other countries.

U.S. Government Rights – Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements.

This distribution may include materials developed by third parties.

Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.

Sun, Sun Microsystems, the Sun logo, the Solaris logo, the Java Coffee Cup logo, docs.sun.com, Java, and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK and SunTMGraphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license agreements.

Products covered by and information contained in this publication are controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical or biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited.

DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Copyright 2007 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. Tous droits réservés.

Sun Microsystems, Inc. détient les droits de propriété intellectuelle relatifs à la technologie incorporée dans le produit qui est décrit dans ce document. En particulier, et ce sans limitation, ces droits de propriété intellectuelle peuvent inclure un ou plusieurs brevets américains ou des applications de brevet en attente aux Etats-Unis et dans d'autres pays.

Cette distribution peut comprendre des composants développés par des tierces personnes.

Certaines composants de ce produit peuvent être dérivées du logiciel Berkeley BSD, licenciés par l'Université de Californie. UNIX est une marque déposée aux Etats-Unis et dans d'autres pays; elle est licenciée exclusivement par X/Open Company, Ltd.

Sun, Sun Microsystems, le logo Sun, le logo Solaris, le logo Java Coffee Cup, docs.sun.com, Java et Solaris sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d'autres pays. Toutes les marques SPARC sont utilisées sous licence et sont des marques de fabrique ou des marques déposées de SPARC International, Inc. aux Etats-Unis et dans d'autres pays. Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.

L'interface d'utilisation graphique OPEN LOOK et Sun a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept des interfaces d'utilisation visuelle ou graphique pour l'industrie de l'informatique. Sun détient une licence non exclusive de Xerox sur l'interface d'utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l'interface d'utilisation graphique OPEN LOOK et qui, en outre, se conforment aux licences écrites de Sun.

Les produits qui font l'objet de cette publication et les informations qu'il contient sont régis par la legislation américaine en matière de contrôle des exportations et peuvent être soumis au droit d'autres pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour des armes nucléaires, des missiles, des armes chimiques ou biologiques ou pour le nucléaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou réexportations vers des pays sous embargo des Etats-Unis, ou vers des entités figurant sur les listes d'exclusion d'exportation américaines, y compris, mais de manière non exclusive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une façon directe ou indirecte, aux exportations des produits ou des services qui sont régis par la legislation américaine en matière de contrôle des exportations et la liste de ressortissants spécifiquement designés, sont rigoureusement interdites.

(3)

Contents

Preface...29

Part I Introduction...39

1 Overview...41

Java EE Application Model ... 42

Distributed Multitiered Applications ... 42

Security ... 43

Java EE Components ... 44

Java EE Clients ... 44

Web Components ... 46

Business Components ... 47

Enterprise Information System Tier ... 48

Java EE Containers ... 48

Container Services ... 49

Container Types ... 49

Web Services Support ... 51

XML ... 51

SOAP Transport Protocol ... 52

WSDL Standard Format ... 52

UDDI and ebXML Standard Formats ... 52

Java EE Application Assembly and Deployment ... 52

Packaging Applications ... 53

Development Roles ... 54

Java EE Product Provider ... 55

Tool Provider ... 55

(4)

Application Assembler ... 56

Application Deployer and Administrator ... 56

Java EE 5 APIs ... 57

Enterprise JavaBeans Technology ... 57

Java Servlet Technology ... 58

JavaServer Pages Technology ... 58

JavaServer Pages Standard Tag Library ... 58

JavaServer Faces ... 58

Java Message Service API ... 59

Java Transaction API ... 59

JavaMail API ... 59

JavaBeans Activation Framework ... 59

Java API for XML Processing ... 60

Java API for XML Web Services (JAX-WS) ... 60

Java Architecture for XML Binding (JAXB) ... 60

SOAP with Attachments API for Java ... 60

Java API for XML Registries ... 61

J2EE Connector Architecture ... 61

Java Database Connectivity API ... 61

Java Persistence API ... 62

Java Naming and Directory Interface ... 62

Java Authentication and Authorization Service ... 62

Simplified Systems Integration ... 63

Sun Java System Application Server Platform Edition 9 ... 63

Tools ... 63

2 Using the Tutorial Examples... 65

Required Software ... 65

Tutorial Bundle ... 65

Java Platform, Standard Edition ... 66

Sun Java System Application Server 9.1 ... 66

NetBeans IDE ... 67

Apache Ant ... 68

Starting and Stopping the Application Server ... 68

Starting the Admin Console ... 69

(5)

Starting and Stopping the Java DB Database Server ... 69

Building the Examples ... 70

Building the Examples Using NetBeans IDE ... 70

Building the Examples on the Command-Line Using Ant ... 70

Tutorial Example Directory Structure ... 71

Debugging Java EE Applications ... 72

Using the Server Log ... 72

Using a Debugger ... 73

Part II The Web Tier... 75

3 Getting Started with Web Applications... 77

Web Applications ... 77

Web Application Life Cycle ... 80

Web Modules ... 81

Packaging Web Modules ... 83

Deploying a WAR File ... 84

Testing Deployed Web Modules ... 85

Listing Deployed Web Modules ... 86

Updating Web Modules ... 86

Undeploying Web Modules ... 88

Configuring Web Applications ... 89

Mapping URLs to Web Components ... 89

Declaring Welcome Files ... 91

Setting Initialization Parameters ... 92

Mapping Errors to Error Screens ... 93

Declaring Resource References ... 94

Duke’s Bookstore Examples ... 96

Accessing Databases from Web Applications ... 97

Populating the Example Database ... 97

Creating a Data Source in the Application Server ... 98

Further Information about Web Applications ... 98

(6)

4 Java Servlet Technology...99

What Is a Servlet? ... 99

The Example Servlets ... 100

Troubleshooting Duke's Bookstore Database Problems ... 102

Servlet Life Cycle ... 102

Handling Servlet Life-Cycle Events ... 103

Handling Servlet Errors ... 105

Sharing Information ... 105

Using Scope Objects ... 105

Controlling Concurrent Access to Shared Resources ... 106

Accessing Databases ... 107

Initializing a Servlet ... 109

Writing Service Methods ... 110

Getting Information from Requests ... 110

Constructing Responses ... 112

Filtering Requests and Responses ... 114

Programming Filters ... 115

Programming Customized Requests and Responses ... 117

Specifying Filter Mappings ... 119

Invoking Other Web Resources ... 122

Including Other Resources in the Response ... 122

Transferring Control to Another Web Component ... 124

Accessing the Web Context ... 124

Maintaining Client State ... 125

Accessing a Session ... 125

Associating Objects with a Session ... 126

Session Management ... 126

Session Tracking ... 127

Finalizing a Servlet ... 128

Tracking Service Requests ... 129

Notifying Methods to Shut Down ... 129

Creating Polite Long-Running Methods ... 130

Further Information about Java Servlet Technology ... 131

(7)

5 JavaServer Pages Technology ...133

What Is a JSP Page? ... 133

A Simple JSP Page Example ... 134

The Example JSP Pages ... 136

The Life Cycle of a JSP Page ... 142

Translation and Compilation ... 142

Execution ... 143

Creating Static Content ... 144

Response and Page Encoding ... 145

Creating Dynamic Content ... 145

Using Objects within JSP Pages ... 145

Unified Expression Language ... 146

Immediate and Deferred Evaluation Syntax ... 148

Value and Method Expressions ... 150

Defining a Tag Attribute Type ... 156

Deactivating Expression Evaluation ... 157

Literal Expressions ... 158

Resolving Expressions ... 160

Implicit Objects ... 162

Operators ... 163

Reserved Words ... 163

Examples of EL Expressions ... 164

Functions ... 165

JavaBeans Components ... 167

JavaBeans Component Design Conventions ... 167

Creating and Using a JavaBeans Component ... 168

Setting JavaBeans Component Properties ... 169

Retrieving JavaBeans Component Properties ... 171

Using Custom Tags ... 172

Declaring Tag Libraries ... 172

Including the Tag Library Implementation ... 174

Reusing Content in JSP Pages ... 175

Transferring Control to Another Web Component ... 176

jsp:paramElement ... 176

Including an Applet ... 176

Setting Properties for Groups of JSP Pages ... 179

(8)

Deactivating EL Expression Evaluation ... 180

Further Information about JavaServer Pages Technology ... 183

6 JavaServer Pages Documents...185

The Example JSP Document ... 185

Creating a JSP Document ... 188

Declaring Tag Libraries ... 190

Including Directives in a JSP Document ... 191

Creating Static and Dynamic Content ... 193

Using thejsp:rootElement ... 196

Using thejsp:outputElement ... 196

Identifying the JSP Document to the Container ... 200

7 JavaServer Pages Standard Tag Library... 201

The Example JSP Pages ... 201

Using JSTL ... 203

Tag Collaboration ... 204

Core Tag Library ... 205

Variable Support Tags ... 205

Flow Control Tags ... 206

URL Tags ... 210

Miscellaneous Tags ... 211

XML Tag Library ... 211

Core Tags ... 213

Flow Control Tags ... 214

Transformation Tags ... 215

Internationalization Tag Library ... 215

Setting the Locale ... 216

Messaging Tags ... 216

Formatting Tags ... 217

SQL Tag Library ... 218

queryTag Result Interface ... 220

JSTL Functions ... 222

Further Information about JSTL ... 223

(9)

8 Custom Tags in JSP Pages... 225

What Is a Custom Tag? ... 226

The Example JSP Pages ... 226

Types of Tags ... 229

Tags with Attributes ... 229

Tags with Bodies ... 232

Tags That Define Variables ... 232

Communication between Tags ... 233

Encapsulating Reusable Content Using Tag Files ... 233

Tag File Location ... 235

Tag File Directives ... 235

Evaluating Fragments Passed to Tag Files ... 242

Custom Tag Examples ... 243

Tag Library Descriptors ... 247

Top-Level Tag Library Descriptor Elements ... 248

Declaring Tag Files ... 249

Declaring Tag Handlers ... 251

Declaring Tag Attributes for Tag Handlers ... 252

Declaring Tag Variables for Tag Handlers ... 254

Programming Simple Tag Handlers ... 256

Including Tag Handlers in Web Applications ... 256

How Is a Simple Tag Handler Invoked? ... 256

Tag Handlers for Basic Tags ... 257

Tag Handlers for Tags with Attributes ... 257

Tag Handlers for Tags with Bodies ... 260

Tag Handlers for Tags That Define Variables ... 261

Cooperating Tags ... 263

Tag Handler Examples ... 265

9 Scripting in JSP Pages...273

The Example JSP Pages ... 273

Using Scripting ... 275

Disabling Scripting ... 275

JSP Declarations ... 276

Initializing and Finalizing a JSP Page ... 276

(10)

JSP Scriptlets ... 277

JSP Expressions ... 277

Programming Tags That Accept Scripting Elements ... 278

TLD Elements ... 278

Tag Handlers ... 278

Tags with Bodies ... 280

Cooperating Tags ... 282

Tags That Define Variables ... 284

10 JavaServer Faces Technology...285

JavaServer Faces Technology User Interface ... 285

JavaServer Faces Technology Benefits ... 286

What Is a JavaServer Faces Application? ... 287

A Simple JavaServer Faces Application ... 287

Steps in the Development Process ... 288

Mapping theFacesServletInstance ... 289

Creating the Pages ... 290

Defining Page Navigation ... 296

Configuring Error Messages ... 297

Developing the Beans ... 298

Adding Managed Bean Declarations ... 298

User Interface Component Model ... 299

User Interface Component Classes ... 300

Component Rendering Model ... 301

Conversion Model ... 304

Event and Listener Model ... 305

Validation Model ... 307

Navigation Model ... 307

Backing Beans ... 309

Creating a Backing Bean Class ... 309

The Life Cycle of a JavaServer Faces Page ... 313

Restore View Phase ... 315

Further Information about JavaServer Faces Technology ... 318

(11)

11 Using JavaServer Faces Technology in JSP Pages... 319

The Example JavaServer Faces Application ... 319

Setting Up a Page ... 322

Using the Core Tags ... 325

Adding UI Components to a Page Using the HTML Component Tags ... 327

UI Component Tag Attributes ... 327

Adding a Form Component ... 329

Using Text Components ... 330

Using Command Components for Performing Actions and Navigation ... 335

Using Data-Bound Table Components ... 337

Adding Graphics and Images with thegraphicImageTag ... 340

Laying Out Components with theUIPanelComponent ... 341

Rendering Components for Selecting One Value ... 343

Rendering Components for Selecting Multiple Values ... 345

TheUISelectItem,UISelectItems, andUISelectItemGroupComponents ... 346

Displaying Error Messages with themessageandmessagesTags ... 349

Using Localized Data ... 350

Loading a Resource Bundle ... 351

Referencing Localized Static Data ... 352

Referencing Error Messages ... 352

Using the Standard Converters ... 354

Converting a Component’s Value ... 355

UsingDateTimeConverter... 356

UsingNumberConverter... 357

Registering Listeners on Components ... 359

Registering a Value-Change Listener on a Component ... 359

Registering an Action Listener on a Component ... 360

Using the Standard Validators ... 361

Validating a Component’s Value ... 362

Using theLongRangeValidator ... 363

Binding Component Values and Instances to External Data Sources ... 364

Binding a Component Value to a Property ... 365

Binding a Component Value to an Implicit Object ... 366

Binding a Component Instance to a Bean Property ... 368

Binding Converters, Listeners, and Validators to Backing Bean Properties ... 369

Referencing a Backing Bean Method ... 370

(12)

Referencing a Method That Performs Navigation ... 371

Referencing a Method That Handles an Action Event ... 371

Referencing a Method That Performs Validation ... 372

Referencing a Method That Handles a Value-change Event ... 372

Using Custom Objects ... 373

Using a Custom Converter ... 374

Using a Custom Validator ... 375

Using a Custom Component ... 376

12 Developing with JavaServer Faces Technology... 379

Writing Bean Properties ... 379

Writing Properties Bound to Component Values ... 380

Writing Properties Bound to Component Instances ... 388

Writing Properties Bound to Converters, Listeners, or Validators ... 389

Performing Localization ... 390

Creating a Resource Bundle ... 390

Localizing Dynamic Data ... 390

Localizing Messages ... 391

Creating a Custom Converter ... 393

Implementing an Event Listener ... 395

Implementing Value-Change Listeners ... 396

Implementing Action Listeners ... 397

Creating a Custom Validator ... 398

Implementing the Validator Interface ... 399

Creating a Custom Tag ... 402

Writing Backing Bean Methods ... 404

Writing a Method to Handle Navigation ... 404

Writing a Method to Handle an Action Event ... 406

Writing a Method to Perform Validation ... 406

Writing a Method to Handle a Value-Change Event ... 407

13 Creating Custom UI Components...409

Determining Whether You Need a Custom Component or Renderer ... 410

When to Use a Custom Component ... 410

When to Use a Custom Renderer ... 411

(13)

Component, Renderer, and Tag Combinations ... 412

Understanding the Image Map Example ... 413

Why Use JavaServer Faces Technology to Implement an Image Map? ... 413

Understanding the Rendered HTML ... 413

Understanding the JSP Page ... 414

Configuring Model Data ... 416

Summary of the Application Classes ... 417

Steps for Creating a Custom Component ... 418

Creating Custom Component Classes ... 419

Specifying the Component Family ... 421

Performing Encoding ... 422

Performing Decoding ... 424

Enabling Component Properties to Accept Expressions ... 424

Saving and Restoring State ... 426

Delegating Rendering to a Renderer ... 427

Creating the Renderer Class ... 427

Identifying the Renderer Type ... 429

Handling Events for Custom Components ... 429

Creating the Component Tag Handler ... 430

Retrieving the Component Type ... 431

Setting Component Property Values ... 431

Providing the Renderer Type ... 433

Releasing Resources ... 434

Defining the Custom Component Tag in a Tag Library Descriptor ... 434

14 Configuring JavaServer Faces Applications...437

Application Configuration Resource File ... 437

Configuring Beans ... 439

Using themanaged-beanElement ... 439

Initializing Properties Using themanaged-propertyElement ... 441

Initializing Maps and Lists ... 447

Registering Custom Error Messages ... 448

Registering Custom Localized Static Text ... 449

Registering a Custom Validator ... 450

Registering a Custom Converter ... 451

(14)

Configuring Navigation Rules ... 451

Registering a Custom Renderer with a Render Kit ... 455

Registering a Custom Component ... 457

Basic Requirements of a JavaServer Faces Application ... 458

Configuring an Application with a Deployment Descriptor ... 459

Including the Required JAR Files ... 466

Including the Classes, Pages, and Other Resources ... 466

15 Internationalizing and Localizing Web Applications... 467

Java Platform Localization Classes ... 467

Providing Localized Messages and Labels ... 468

Establishing the Locale ... 468

Setting the Resource Bundle ... 469

Retrieving Localized Messages ... 470

Date and Number Formatting ... 471

Character Sets and Encodings ... 472

Character Sets ... 472

Character Encoding ... 473

Further Information about Internationalizing Web Applications ... 475

Part III Web Services...477

16 Building Web Services with JAX-WS... 479

Setting the Port ... 480

Creating a Simple Web Service and Client with JAX-WS ... 480

Requirements of a JAX-WS Endpoint ... 481

Coding the Service Endpoint Implementation Class ... 482

Building, Packaging, and Deploying the Service ... 482

Testing the Service without a Client ... 484

A Simple JAX-WS Client ... 484

Types Supported by JAX-WS ... 486

Web Services Interoperability and JAX-WS ... 487

Further Information about JAX-WS ... 487

(15)

17 Binding between XML Schema and Java Classes... 489

JAXB Architecture ... 489

Architectural Overview ... 489

The JAXB Binding Process ... 490

More about Unmarshalling ... 492

More about Marshalling ... 492

More about Validation ... 492

Representing XML Content ... 492

Java Representation of XML Schema ... 492

Binding XML Schemas ... 493

Simple Type Definitions ... 493

Default Data Type Bindings ... 493

Customizing Generated Classes and Java Program Elements ... 495

Schema-to-Java ... 495

Java-to-Schema ... 496

JAXB Examples ... 501

JAXB Compiler Options ... 503

JAXB Schema Generator Option ... 505

About the Schema-to-Java Bindings ... 505

Schema-Derived JAXB Classes ... 508

Basic JAXB Examples ... 511

Modify Marshal Example ... 511

Unmarshal Validate Example ... 512

Customizing JAXB Bindings ... 514

Why Customize? ... 515

Customization Overview ... 515

Customize Inline Example ... 526

Datatype Converter Example ... 531

Binding Declaration Files ... 533

External Customize Example ... 536

Java-to-Schema Examples ... 536

Create Marshal Example ... 537

XmlAccessorOrder Example ... 538

XmlAdapter Field Example ... 540

XmlAttribute Field Example ... 543

XmlRootElement Example ... 544

(16)

XmlSchemaType Class Example ... 545

XmlType Example ... 546

Further Information about JAXB ... 548

18 Streaming API for XML...549

Why StAX? ... 549

Streaming versus DOM ... 549

Pull Parsing versus Push Parsing ... 550

StAX Use Cases ... 551

Comparing StAX to Other JAXP APIs ... 551

StAX API ... 552

Cursor API ... 553

Iterator API ... 553

Choosing between Cursor and Iterator APIs ... 557

Using StAX ... 559

StAX Factory Classes ... 559

Resources, Namespaces, and Errors ... 561

Reading XML Streams ... 561

Writing XML Streams ... 564

Sun’s Streaming XML Parser Implementation ... 566

Reporting CDATA Events ... 566

Streaming XML Parser Factories Implementation ... 566

Example Code ... 567

Example Code Organization ... 567

Example XML Document ... 568

Cursor Example ... 568

Cursor-to-Event Example ... 571

Event Example ... 573

Filter Example ... 575

Read-and-Write Example ... 578

Writer Example ... 580

Further Information about StAX ... 583

19 SOAP with Attachments API for Java... 585

Overview of SAAJ ... 586

(17)

SAAJ Messages ... 586

SAAJ Connections ... 589

SAAJ Tutorial ... 590

Creating and Sending a Simple Message ... 591

Adding Content to the Header ... 598

Adding Content to theSOAPPartObject ... 599

Adding a Document to the SOAP Body ... 600

Manipulating Message Content Using SAAJ or DOM APIs ... 601

Adding Attachments ... 601

Adding Attributes ... 603

Using SOAP Faults ... 608

Code Examples ... 613

Request Example ... 613

Header Example ... 614

DOM and DOMSource Examples ... 617

Attachments Example ... 622

SOAP Fault Example ... 624

Further Information about SAAJ ... 627

Part IV Enterprise Beans...629

20 Enterprise Beans...631

What Is an Enterprise Bean? ... 631

Benefits of Enterprise Beans ... 631

When to Use Enterprise Beans ... 632

Types of Enterprise Beans ... 632

What Is a Session Bean? ... 633

State Management Modes ... 633

When to Use Session Beans ... 634

What Is a Message-Driven Bean? ... 634

What Makes Message-Driven Beans Different from Session Beans? ... 635

When to Use Message-Driven Beans ... 636

Defining Client Access with Interfaces ... 636

Remote Clients ... 636

Local Clients ... 637

(18)

Deciding on Remote or Local Access ... 638

Web Service Clients ... 639

Method Parameters and Access ... 639

The Contents of an Enterprise Bean ... 640

Naming Conventions for Enterprise Beans ... 641

The Life Cycles of Enterprise Beans ... 641

The Life Cycle of a Stateful Session Bean ... 642

The Life Cycle of a Stateless Session Bean ... 642

The Life Cycle of a Message-Driven Bean ... 643

Further Information about Enterprise Beans ... 644

21 Getting Started with Enterprise Beans... 645

Creating the Enterprise Bean ... 645

Coding the Enterprise Bean ... 646

Compiling and Packaging theconverterExample ... 647

Creating theconverterApplication Client ... 648

Coding theconverterApplication Client ... 648

Compiling theconverterApplication Client ... 650

Creating theconverterWeb Client ... 650

Coding theconverterWeb Client ... 650

Compiling theconverterWeb Client ... 652

Deploying theconverterJava EE Application ... 652

Deploying theconverterExample Using NetBeans IDE ... 652

Deploying theconverterExample Using Ant ... 652

Running theconverterApplication Client ... 653

Running theconverterApplication Client Using NetBeans IDE ... 653

Running theconverterApplication Client Using Ant ... 653

Running theconverterWeb Client ... 654

Modifying the Java EE Application ... 654

Modifying a Class File ... 654

22 Session Bean Examples...657

ThecartExample ... 657

The Business Interface ... 658

Session Bean Class ... 658

(19)

The Remove Method ... 662

Helper Classes ... 662

Building, Packaging, Deploying, and Running thecartExample ... 662

Undeploying thecartExample ... 665

A Web Service Example:helloservice... 665

The Web Service Endpoint Implementation Class ... 666

Stateless Session Bean Implementation Class ... 666

Building, Packaging, Deploying, and Testing thehelloserviceExample ... 667

Using the Timer Service ... 669

TheTimeoutMethod ... 669

Creating Timers ... 669

Canceling and Saving Timers ... 670

Getting Timer Information ... 670

Transactions and Timers ... 670

ThetimersessionExample ... 671

Building, Packaging, Deploying, and Running thetimersessionExample ... 672

Handling Exceptions ... 674

23 A Message-Driven Bean Example...675

simplemessageExample Application Overview ... 675

ThesimplemessageApplication Client ... 676

The Message-Driven Bean Class ... 677

TheonMessageMethod ... 677

Packaging, Deploying, and Running thesimplemessageExample ... 678

Creating the Administered Objects for thesimplemessageExample ... 679

Building, Deploying, and Running thesimplemessageApplication Using NetBeans IDE ... 679

Building, Deploying, and Running thesimplemessageApplication Using Ant ... 680

Removing the Administered Objects for thesimplemessageExample ... 681

Creating Deployment Descriptors for Message-Driven Beans ... 682

Part V Persistence...683

24 Introduction to the Java Persistence API ... 685

Entities ... 685

(20)

Requirements for Entity Classes ... 685

Persistent Fields and Properties in Entity Classes ... 686

Primary Keys in Entities ... 688

Multiplicity in Entity Relationships ... 689

Direction in Entity Relationships ... 690

Entity Inheritance ... 691

Managing Entities ... 696

The Persistence Context ... 696

TheEntityManagerInterface ... 696

Persistence Units ... 701

25 Persistence in the Web Tier... 703

Accessing Databases from Web Applications ... 703

Defining the Persistence Unit ... 704

Creating an Entity Class ... 705

Obtaining Access to an Entity Manager ... 706

Accessing Data from the Database ... 708

Updating Data in the Database ... 708

26 Persistence in the EJB Tier... 711

TheorderApplication ... 711

Entity Relationships in theorderApplication ... 711

Primary Keys in theorderApplication ... 714

Entity Mapped to More Than One Database Table ... 717

Cascade Operations in theorderApplication ... 718

BLOB and CLOB Database Types in theorderApplication ... 718

Temporal Types in theorderApplication ... 719

Managing theorderApplication’s Entities ... 719

Building and Running theorderApplication ... 721

TherosterApplication ... 726

Relationships in therosterApplication ... 726

Entity Inheritance in therosterApplication ... 727

Automatic Table Generation in therosterApplication ... 729

Building and Running therosterApplication ... 729

(21)

27 The Java Persistence Query Language ... 733

Query Language Terminology ... 733

Simplified Query Language Syntax ... 734

Select Statements ... 734

Update and Delete Statements ... 734

Example Queries ... 735

Simple Queries ... 735

Queries That Navigate to Related Entities ... 736

Queries with Other Conditional Expressions ... 738

Bulk Updates and Deletes ... 740

Full Query Language Syntax ... 740

BNF Symbols ... 740

BNF Grammar of the Java Persistence Query Language ... 741

FROMClause ... 745

Path Expressions ... 749

WHEREClause ... 751

SELECTClause ... 759

ORDER BYClause ... 761

TheGROUP BYClause ... 762

Part VI Services...763

28 Introduction to Security in the Java EE Platform... 765

Overview of Java EE Security ... 766

A Simple Security Example ... 766

Security Functions ... 769

Characteristics of Application Security ... 770

Security Implementation Mechanisms ... 771

Java SE Security Implementation Mechanisms ... 771

Java EE Security Implementation Mechanisms ... 772

Securing Containers ... 774

Using Deployment Descriptors for Declarative Security ... 774

Using Annotations ... 775

Using Programmatic Security ... 776

Securing the Application Server ... 777

(22)

Working with Realms, Users, Groups, and Roles ... 777 What Are Realms, Users, Groups, and Roles? ... 778 Managing Users and Groups on the Application Server ... 781 Setting Up Security Roles ... 782 Mapping Roles to Users and Groups ... 784 Establishing a Secure Connection Using SSL ... 785 Installing and Configuring SSL Support ... 785 Specifying a Secure Connection in Your Application Deployment Descriptor ... 786 Verifying SSL Support ... 787 Working with Digital Certificates ... 788 Enabling Mutual Authentication over SSL ... 793 Further Information about Security ... 795

29 Securing Java EE Applications...797

Securing Enterprise Beans ... 798 Accessing an Enterprise Bean Caller’s Security Context ... 799 Declaring Security Role Names Referenced from Enterprise Bean Code ... 801 Defining a Security View of Enterprise Beans ... 804 Using Enterprise Bean Security Annotations ... 815 Using Enterprise Bean Security Deployment Descriptor Elements ... 816 Configuring IOR Security ... 817 Deploying Secure Enterprise Beans ... 819 Enterprise Bean Example Applications ... 820 Example: Securing an Enterprise Bean ... 820 Example: Using theisCallerInRoleandgetCallerPrincipalMethods ... 826 Discussion: Securing the Duke’s Bank Example ... 831 Securing Application Clients ... 832 Using Login Modules ... 832 Using Programmatic Login ... 833 Securing EIS Applications ... 834 Container-Managed Sign-On ... 834 Component-Managed Sign-On ... 834 Configuring Resource Adapter Security ... 835 Mapping an Application Principal to EIS Principals ... 837

(23)

30 Securing Web Applications...839 Overview of Web Application Security ... 840 Working with Security Roles ... 841 Declaring Security Roles ... 841 Mapping Security Roles to Application Server Groups ... 844 Checking Caller Identity Programmatically ... 845 Declaring and Linking Role References ... 846 Defining Security Requirements for Web Applications ... 848 Declaring Security Requirements Using Annotations ... 849 Declaring Security Requirements in a Deployment Descriptor ... 851 Specifying a Secure Connection ... 857 Specifying an Authentication Mechanism ... 858 Examples: Securing Web Applications ... 867 Example: Using Form-Based Authentication with a JSP Page ... 868 Example: Basic Authentication with a Servlet ... 877 Example: Basic Authentication with JAX-WS ... 885

31 The Java Message Service API... 893

Overview of the JMS API ... 893 What Is Messaging? ... 893 What Is the JMS API? ... 894 When Can You Use the JMS API? ... 894 How Does the JMS API Work with the Java EE Platform? ... 896 Basic JMS API Concepts ... 896 JMS API Architecture ... 897 Messaging Domains ... 898 Message Consumption ... 900 The JMS API Programming Model ... 900 JMS Administered Objects ... 901 JMS Connections ... 903 JMS Sessions ... 904 JMS Message Producers ... 904 JMS Message Consumers ... 905 JMS Messages ... 907 JMS Queue Browsers ... 909

(24)

JMS Exception Handling ... 910 Writing Simple JMS Client Applications ... 911 A Simple Example of Synchronous Message Receives ... 911 A Simple Example of Asynchronous Message Consumption ... 920 A Simple Example of Browsing Messages in a Queue ... 926 Running JMS Client Programs on Multiple Systems ... 931 Creating Robust JMS Applications ... 935 Using Basic Reliability Mechanisms ... 936 Using Advanced Reliability Mechanisms ... 942 Using the JMS API in a Java EE Application ... 954 Using@ResourceAnnotations in Java EE Components ... 954 Using Session Beans to Produce and to Synchronously Receive Messages ... 955 Using Message-Driven Beans to Receive Messages Asynchronously ... 956 Managing Distributed Transactions ... 958 Using the JMS API with Application Clients and Web Components ... 960 Further Information about JMS ... 961

32 Java EE Examples Using the JMS API... 963

A Java EE Application That Uses the JMS API with a Session Bean ... 964 Writing the Application Components for theclientsessionmdbExample ... 964 Creating Resources for theclientsessionmdbExample ... 967 Building, Deploying, and Running theclientsessionmdbExample Using NetBeans IDE ... 967 Building, Deploying, and Running theclientsessionmdbExample Using Ant ... 969 A Java EE Application That Uses the JMS API with an Entity ... 970 Overview of theclientmdbentityExample Application ... 970 Writing the Application Components for theclientmdbentityExample ... 972 Creating Resources for theclientmdbentityExample ... 974 Building, Deploying, and Running theclientmdbentityExample Using NetBeans IDE ... 975 Building, Deploying, and Running theclientmdbentityExample Using Ant ... 977 An Application Example That Consumes Messages from a Remote Server ... 979 Overview of theconsumeremoteExample Modules ... 979 Writing the Module Components for theconsumeremoteExample ... 980 Creating Resources for theconsumeremoteExample ... 981 Using Two Application Servers for theconsumeremoteExample ... 981

(25)

Building, Deploying, and Running theconsumeremoteModules Using NetBeans IDE ... 982 Building, Deploying, and Running theconsumeremoteModules Using Ant ... 983 An Application Example That Deploys a Message-Driven Bean on Two Servers ... 985 Overview of thesendremoteExample Modules ... 986 Writing the Module Components for thesendremoteExample ... 987 Creating Resources for thesendremoteExample ... 988 Using Two Application Servers for thesendremoteExample ... 989 Building, Deploying, and Running thesendremoteModules Using NetBeans IDE ... 989 Building, Deploying, and Running thesendremoteModules Using Ant ... 992

33 Transactions... 997

What Is a Transaction? ... 997 Container-Managed Transactions ... 998 Transaction Attributes ... 998 Rolling Back a Container-Managed Transaction ... 1002 Synchronizing a Session Bean’s Instance Variables ... 1002 Methods Not Allowed in Container-Managed Transactions ... 1003 Bean-Managed Transactions ... 1003 JTA Transactions ... 1004 Returning without Committing ... 1004 Methods Not Allowed in Bean-Managed Transactions ... 1005 Transaction Timeouts ... 1005 Updating Multiple Databases ... 1005 Transactions in Web Components ... 1007

34 Resource Connections ... 1009

Resources and JNDI Naming ... 1009

DataSourceObjects and Connection Pools ... 1010 Resource Injection ... 1011 Field-Based Injection ... 1012 Method-Based Injection ... 1013 Class-Based Injection ... 1014 TheconfirmerExample Application ... 1014 Running theconfirmerExample Application ... 1015 Further Information about Resources ... 1018

(26)

35 Connector Architecture... 1019 About Resource Adapters ... 1019 Resource Adapter Contracts ... 1021 Management Contracts ... 1021 Outbound Contracts ... 1022 Inbound Contracts ... 1023 Common Client Interface ... 1023 Further Information about the Connector Architecture ... 1025

Part VII Case Studies...1027

36 The Coffee Break Application...1029

Overview of the Coffee Break Application ... 1029 Common Code ... 1031 JAX-WS Coffee Supplier Service ... 1031 Service Implementation ... 1031 SAAJ Coffee Supplier Service ... 1032 SAAJ Client ... 1033 SAAJ Service ... 1040 Coffee Break Server ... 1046 JSP Pages ... 1046 JavaBeans Components ... 1048 TheRetailPriceListServletServlet ... 1050 Resource Configuration ... 1050 Building, Packaging, Deploying, and Running the Coffee Break Application ... 1051 Setting the Port ... 1052 Building, Packaging, and Deploying the JAX-WS Coffee Supplier Service ... 1052 Building, Packaging, and Deploying the SAAJ Coffee Supplier Service ... 1053 Building, Packaging, and Deploying the Coffee Break Server ... 1053 Running the Coffee Break Client ... 1054 Removing the Coffee Break Application ... 1056

37 The Duke’s Bank Application...1057

Overview of the Duke’s Bank Application ... 1057

(27)

Enterprise Beans ... 1058 Session Beans ... 1059 Java Persistence Entities ... 1061 Helper Classes ... 1061 Database Tables ... 1062 Protecting the Enterprise Beans ... 1063 Application Client ... 1064 The Classes and Their Relationships ... 1065

BankAdminClass ... 1065 Web Client ... 1066 Design Strategies ... 1068 Client Components ... 1069 Request Processing ... 1071 Protecting the Web Client Resources ... 1073 Building, Packaging, Deploying, and Running the Duke's Bank Application ... 1075 Setting Up the Servers ... 1075 Building, Packaging, and Deploying Duke’s Bank Using NetBeans IDE ... 1076 Building, Packaging, and Deploying Duke’s Bank Using Ant ... 1077 Running the Duke's Bank Application Client Using NetBeans IDE ... 1077 Running the Duke's Bank Application Client Using Ant ... 1077 Running the Duke's Bank Web Client ... 1078

Part VIII Appendixes...1081

A Java Encoding Schemes...1083

Further Information about Character Encoding ... 1084

B Preparation for Java EE Certification Exams... 1085

CX-310-081: Sun Certified Web Component Developer ... 1086 SL-351–EE5: Business Component Development with Enterprise JavaBeans Technology .. 1086

C About the Authors...1089

Index... 1091

(28)
(29)

Preface

This tutorial is a guide to developing enterprise applications for the JavaTM

Platform, Enterprise Edition 5 (Java EE 5).

This preface contains information about and conventions for the entire Sun Java System Application Server documentation set.

Before You Read This Book

Before proceeding with this tutorial, you should have a good knowledge of the Java

programming language. A good way to get to that point is to work throughThe Java Tutorial,

Fourth Edition, Sharon Zakhour et al. (Addison-Wesley, 2006). You should also be familiar with the Java DataBase Connectivity (JDBCTM

) and relational database features described inJDBC API Tutorial and Reference, Third Edition, Maydene Fisher et al. (Addison-Wesley, 2003).

How This Book Is Organized

The Java EE 5 platform is quite large, and this tutorial reflects this. However, you don’t have to digest everything in it at once. The tutorial has been divided into parts to help you navigate the content more easily.

This tutorial opens with an introductory chapter, which you should read before proceeding to any specific technology area.Chapter 1, “Overview”covers the Java EE 5 platform architecture and APIs, the Sun Java System Application Server 9.1, and how to use the this tutorial's examples.

When you have digested the basics, you can delve into one or more of the five main technology areas listed next. Because there are dependencies between some of the chapters,Figure P–1

contains a roadmap for navigating through the tutorial.

■ The web-tier technology chapters inPart IIcover the components used in developing the

presentation layer of a Java EE 5 or stand-alone web application:

■ Java Servlet

■ JavaServer PagesTM(JSPTM)

(30)

■ JavaServerTMFaces

■ Web application internationalization and localization

■ The web services technology chapters inPart IIIcover the APIs used in developing standard

web services:

■ The Java API for XML-based Web Services (JAX-WS) ■ The Java API for XML Binding (JAXB)

■ The Streaming API for XML (StAX)

■ The SOAP with Attachments API for JavaTM(SAAJ)

■ The Enterprise JavaBeansTM(EJBTM) technology chapters inPart IVcover the components

used in developing the business logic of a Java EE 5 application:

■ Session beans ■ Message-driven beans

■ The persistence technology chapters inPart Vcover the Java Persistence API, which is used

for accessing databases from Java EE applications:

■ Introduction to the Java Persistence API ■ Persistence in the Web Tier

■ Persistence in the EJB Tier

■ The Java Persistence Query Language

■ The platform services chapters inPart VIcover the system services used by all the Java EE 5

component technologies:

■ Security

■ Java Message Service ■ Transactions

■ Resource connections

(31)

After you have become familiar with some of the technology areas, you are ready to tackle the case studies inPart VII, which tie together several of the technologies discussed in the tutorial. The Coffee Break Application describes an application that uses the web application and web services APIs. The Duke’s Bank Application describes an application that employs web application technologies, enterprise beans, and the Java Persistence API.

Finally,Part VIIIcontains information about Java encoding schemes and Java EE certification that may be helpful to the Java EE 5 application developer, and information about the tutorial's authors.

Overview (1)

Getting Started with Web Applications (3)

Building Web Services with

JAX-WS (16)

Enterprise Beans (20-23)

Security (28-30)

SAAJ (19) JAXB (17)

Coffee Break Case Study (36) Servlets (4)

JSP (5-9)

JSF (10-14)

l18n and L10n (15)

Duke’s Bank Case Study (37)

JMS (31-32)

Transactions (33)

Resource Connections

(34) STAX (18)

Connectors (35)

Persistence (24-27)

Using the Tutorial Examples

(2)

FIGURE P–1 Roadmap to This Tutorial

(32)

Application Server Documentation Set

The Application Server documentation set describes deployment planning and system installation. The Uniform Resource Locator (URL) for Application Server documentation is

http://docs.sun.com/coll/1343.4. For an introduction to Application Server, refer to the books in the order in which they are listed in the following table.

TABLE P–1 Books in the Application Server Documentation Set

Book Title Description

Documentation Center Application Server documentation topics organized by task and subject.

Release Notes Late-breaking information about the software and the documentation. Includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDKTM), and database drivers.

Quick Start Guide How to get started with the Application Server product.

Installation Guide Installing the software and its components.

Deployment Planning Guide Evaluating your system needs and enterprise to ensure that you deploy the Application Server in a manner that best suits your site. General issues and concerns that you must be aware of when deploying the server are also discussed.

Application Deployment Guide Deployment of applications and application components to the Application Server. Includes information about deployment descriptors.

Developer’s Guide Creating and implementing Java Platform, Enterprise Edition (Java EE platform) applications intended to run on the Application Server that follow the open Java standards model for Java EE components and APIs. Includes information about developer tools, security, debugging, and creating lifecycle modules.

Java EE 5 Tutorial Using Java EE 5 platform technologies and APIs to develop Java EE applications.

Java WSIT Tutorial Developing web applications using the Web Service Interoperability Technologies (WSIT). Describes how, when, and why to use the WSIT technologies and the features and options that each technology supports.

Administration Guide System administration for the Application Server, including configuration, monitoring, security, resource management, and web services management.

High Availability Administration Guide

Post-installation configuration and administration instructions for the high-availability database.

Administration Reference Editing the Application Server configuration file,domain.xml.

Upgrade and Migration Guide Upgrading from an older version of Application Server or migrating Java EE applications from competitive application servers. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications.

(33)

TABLE P–1 Books in the Application Server Documentation Set (Continued)

Book Title Description

Performance Tuning Guide Tuning the Application Server to improve performance.

Troubleshooting Guide Solving Application Server problems.

Error Message Reference Solving Application Server error messages.

Reference Manual Utility commands available with the Application Server; written in man page style. Includes theasadmincommand line interface.

Related Documentation

Application Server can be purchased by itself or as a component of Sun Java Enterprise System (Java ES), a software infrastructure that supports enterprise applications distributed across a network or Internet environment. If you purchased Application Server as a component of Java ES, you should be familiar with the system documentation at

http://docs.sun.com/coll/1286.3. The URL for all documentation about Java ES and its components ishttp://docs.sun.com/prod/entsys.5.

For documentation about other stand-alone Sun Java System server products, go to the following:

■ Message Queue documentation (http://docs.sun.com/coll/1343.4)

■ Directory Server documentation (http://docs.sun.com/coll/1224.1)

■ Web Server documentation (http://docs.sun.com/coll/1308.3)

A JavadocTM

tool reference for packages provided with the Application Server is located at

http://glassfish.dev.java.net/nonav/javaee5/api/index.html. Additionally, the following resources might be useful:

■ TheJava EE 5 Specifications (http://java.sun.com/javaee/5/javatech.html) ■ TheJava EE Blueprints (http://java.sun.com/reference/blueprints/index.html)

For information on creating enterprise applications in the NetBeansTM

Integrated Development Environment (IDE), seehttp://www.netbeans.org/kb/55/index.html.

For information about the Java DB database included with the Application Server, see

http://developers.sun.com/javadb/.

The GlassFish Samples project is a collection of sample applications that demonstrate a broad range of Java EE technologies. The GlassFish Samples are bundled with the Java EE Software Development Kit (SDK), and are also available from the GlassFish Samples project page at

https://glassfish-samples.dev.java.net/.

(34)

Default Paths and File Names

The following table describes the default paths and file names that are used in this book.

TABLE P–2 Default Paths and File Names

Placeholder Description Default Value

tut-install Represents the base installation directory for the Java EE Tutorial.

None. Install the tutorial in a directory without spaces in the path.

java-home Represents the base installation directory for the Java Platform, Standard Edition (Java SE platform).

None. Same value as theJAVA_HOMEenvironment variable.

as-install Represents the base installation directory for the Application Server or the Software Development Kit (SDK) of which the Application Server is a part.

Java ES installations on the SolarisTM

operating system:

/opt/SUNWappserver/appserver

Java ES installations on the Linux operating system:

/opt/sun/appserver/

Other Solaris and Linux non-SDK installations, non-root user:

user’s-home-directory/SUNWappserver

Other Solaris and Linux non-SDK installations, root user:

/opt/SUNWappserver

Solaris and Linux SDK installations:

user’s-home-directory/SDK

Windows, all non-SDK installations:

SystemDrive:\Sun\AppServer

Windows, all SDK installations:

SystemDrive:\Sun\SDK

domain-root-dir Represents the directory containing all Application Server domains.

Java ES Solaris installations:

/var/opt/SUNWappserver/domains/

Java ES Linux installations:

/var/opt/sun/appserver/domains/

All other installations:

(35)

TABLE P–2 Default Paths and File Names (Continued)

Placeholder Description Default Value

domain-dir Represents the directory for a domain.

In configuration files, you might see domain-dirrepresented as follows:

${com.sun.aas.instanceRoot}

domain-root-dir/domain-dir

instance-dir Represents the directory for a server instance. domain-dir/instance-dir

Typographic Conventions

The following table describes the typographic changes that are used in this book.

TABLE P–3 Typographic Conventions

Typeface Meaning Example

AaBbCc123 The names of commands, files, and directories, and onscreen computer output

Edit your.loginfile.

Usels -ato list all files.

machine_name% you have mail.

AaBbCc123 What you type, contrasted with onscreen computer output

machine_name%su

Password:

AaBbCc123 A placeholder to be replaced with a real name or value

The command to remove a file isrmfilename.

AaBbCc123 Book titles, new terms, and terms to be emphasized (note that some emphasized items appear bold online)

Read Chapter 6 in theUser's Guide.

Acacheis a copy that is stored locally.

Donotsave the file.

Symbol Conventions

The following table explains symbols that might be used in this book.

TABLE P–4 Symbol Conventions

Symbol Description Example Meaning

[ ] Contains optional arguments and command options.

(36)

TABLE P–4 Symbol Conventions (Continued)

Symbol Description Example Meaning

{ | } Contains a set of choices for a required command option.

-d {y|n} The-doption requires that you use either theyargument or then argument.

${ } Indicates a variable reference.

${com.sun.javaRoot} References the value of the com.sun.javaRootvariable.

- Joins simultaneous multiple keystrokes.

Control-A Press the Control key while you press the A key.

+ Joins consecutive multiple keystrokes.

Ctrl+A+N Press the Control key, release it, and then press the subsequent keys.

→ Indicates menu item

selection in a graphical user interface.

File→New→Templates From the File menu, choose New.

From the New submenu, choose Templates.

Documentation, Support, and Training

The Sun web site provides information about the following additional resources:

■ Documentation (http://www.sun.com/documentation/)

■ Support (http://www.sun.com/support/)

■ Training (http://www.sun.com/training/)

Searching Sun Product Documentation

Besides searching Sun product documentation from the docs.sun.comSM

web site, you can use a search engine by typing the following syntax in the search field:

search-term site:docs.sun.com

For example, to search for “broker,” type the following:

broker site:docs.sun.com

To include other Sun web sites in your search (for example,java.sun.com,www.sun.com, and

developers.sun.com), usesun.comin place ofdocs.sun.comin the search field.

(37)

Third-Party Web Site References

Third-party URLs are referenced in this document and provide additional, related information.

Note –Sun is not responsible for the availability of third-party web sites mentioned in this document. Sun does not endorse and is not responsible or liable for any content, advertising, products, or other materials that are available on or through such sites or resources. Sun will not be responsible or liable for any actual or alleged damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services that are available on or through such sites or resources.

Sun Welcomes Your Comments

Sun is interested in improving its documentation and welcomes your comments and

suggestions. To share your comments, go tohttp://docs.sun.comand click Send Comments. In the online form, provide the full document title and part number. The part number is a 7-digit or 9-digit number that can be found on the book's title page or in the document's URL. For example, the part number of this book is 819-3669.

(38)
(39)

Introduction

Part One introduces the tutorial and examples.

(40)
(41)

Overview

Developers today increasingly recognize the need for distributed, transactional, and portable applications that leverage the speed, security, and reliability of server-side technology. In the world of information technology, enterprise applications must be designed, built, and produced for less money, with greater speed, and with fewer resources.

With the JavaTM

Platform, Enterprise Edition (Java EE), development of Java enterprise applications has never been easier or faster. The aim of the Java EE 5 platform is to provide developers a powerful set of APIs while reducing development time, reducing application complexity, and improving application performance.

The Java EE 5 platform introduces a simplified programming model. With Java EE 5 technology, XML deployment descriptors are now optional. Instead, a developer can simply enter the information as an annotation directly into a Java source file, and the Java EE server will configure the component at deployment and runtime. These annotations are generally used to embed in a program data that would otherwise be furnished in a deployment descriptor. With annotations, the specification information is put directly in your code next to the program element that it affects.

In the Java EE platform, dependency injection can be applied to all resources that a component needs, effectively hiding the creation and lookup of resources from application code.

Dependency injection can be used in EJB containers, web containers, and application clients. Dependency injection allows the Java EE container to automatically insert references to other required components or resources using annotations.

The Java Persistence API is new to the Java EE 5 platform. The Java Persistence API provides an object/relational mapping for managing relational data in enterprise beans, web components, and application clients. It can also be used in Java SE applications, outside of the Java EE environment.

This tutorial uses examples to describe the features and functionalities available in the Java EE 5 platform for developing enterprise applications. Whether you are a new or experienced Enterprise developer, you should find the examples and accompanying text a valuable and accessible knowledge base for creating your own solutions.

1

(42)

If you are new to Java EE enterprise application development, this chapter is a good place to start. Here you will review development basics, learn about the Java EE architecture and APIs, become acquainted with important terms and concepts, and find out how to approach Java EE application programming, assembly, and deployment.

Java EE Application Model

The Java EE application model begins with the Java programming language and the Java virtual machine. The proven portability, security, and developer productivity they provide forms the basis of the application model. Java EE is designed to support applications that implement enterprise services for customers, employees, suppliers, partners, and others who make demands on or contributions to the enterprise. Such applications are inherently complex, potentially accessing data from a variety of sources and distributing applications to a variety of clients.

To better control and manage these applications, the business functions to support these various users are conducted in the middle tier. The middle tier represents an environment that is closely controlled by an enterprise’s information technology department. The middle tier is typically run on dedicated server hardware and has access to the full services of the enterprise.

The Java EE application model defines an architecture for implementing services as multitier applications that deliver the scalability, accessibility, and manageability needed by

enterprise-level applications. This model partitions the work needed to implement a multitier service into two parts: the business and presentation logic to be implemented by the developer, and the standard system services provided by the Java EE platform. The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multitier service.

Distributed Multitiered Applications

The Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the various application components that make up a Java EE application are installed on different machines depending on the tier in the multitiered Java EE environment to which the application component belongs.

Figure 1–1shows two multitiered Java EE applications divided into the tiers described in the following list. The Java EE application parts shown inFigure 1–1are presented in“Java EE Components” on page 44.

(43)

■ Enterprise information system (EIS)-tier software runs on the EIS server.

Although a Java EE application can consist of the three or four tiers shown inFigure 1–1, Java EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard two-tiered client and server model by placing a multithreaded application server between the client application and back-end storage.

Security

While other enterprise application models require platform-specific security measures in each application, the Java EE security environment enables security constraints to be defined at deployment time. The Java EE platform makes applications portable to a wide variety of security implementations by shielding application developers from the complexity of implementing security features.

The Java EE platform provides standard declarative access control rules that are defined by the developer and interpreted when the application is deployed on the server. Java EE also provides

Application Client

Java EE Application 1 Java EE Application 2

Dynamic HTML Pages

Web Tier

Business Tier

Enterprise Beans Enterprise Beans

Database Database

JSP Pages

EIS Tier

Client Tier ClientMachine

Java EE Server

Database Server

FIGURE 1–1 Multitiered Applications

(44)

standard login mechanisms so application developers do not have to implement these mechanisms in their applications. The same application works in a variety of different security environments without changing the source code.

Java EE Components

Java EE applications are made up of components. AJava EE componentis a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components.

The Java EE specification defines the following Java EE components:

■ Application clients and applets are components that run on the client.

■ Java Servlet, JavaServer Faces, and JavaServer PagesTM(JSPTM) technology components are

web components that run on the server.

■ Enterprise JavaBeansTM(EJBTM) components (enterprise beans) are business components

that run on the server.

Java EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between Java EE components and “standard” Java classes is that Java EE components are assembled into a Java EE application, are verified to be well formed and in compliance with the Java EE specification, and are deployed to production, where they are run and managed by the Java EE server.

Java EE Clients

A Java EE client can be a web client or an application client.

Web Clients

Aweb clientconsists of two parts: (1) dynamic web pages containing various types of markup language (HTML, XML, and so on), which are generated by web components running in the web tier, and (2) a web browser, which renders the pages received from the server.

A web client is sometimes called athin client. Thin clients usually do not query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE server, where they can leverage the security, speed, services, and reliability of Java EE server-side technologies.

(45)

Applets

A web page received from the web tier can include an embedded applet. Anappletis a small client application written in the Java programming language that executes in the Java virtual machine installed in the web browser. However, client systems will likely need the Java Plug-in and possibly a security policy file for the applet to successfully execute in the web browser.

Web components are the preferred API for creating a web client program because no plug-ins or security policy files are needed on the client systems. Also, web components enable cleaner and more modular application design because they provide a way to separate applications programming from web page design. Personnel involved in web page design thus do not need to understand Java programming language syntax to do their jobs.

Application Clients

Anapplication clientruns on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. It typically has a graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible.

Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, an application client can open an HTTP connection to establish communication with a servlet running in the web tier. Application clients written in languages other than Java can interact with Java EE 5 servers, enabling the Java EE 5 platform to interoperate with legacy systems, clients, and non-Java languages.

The JavaBeans

TM

Component Architecture

The server and client tiers might also include components based on the JavaBeans component architecture (JavaBeans components) to manage the data flow between an application client or applet and components running on the Java EE server, or between server components and a database. JavaBeans components are not considered Java EE components by the Java EE specification.

JavaBeans components have properties and havegetandsetmethods for accessing the properties. JavaBeans components used in this way are typically simple in design and implementation but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

Java EE Server Communications

Figure 1–2shows the various elements that can make up the client tier. The client

communicates with the business tier running on the Java EE server either directly or, as in the case of a client running in a browser, by going through JSP pages or servlets running in the web tier.

(46)

Your Java EE application uses a thin browser-based client or thick application client. In deciding which one to use, you should be aware of the trade-offs between keeping functionality on the client and close to the user (thick client) and off-loading as much functionality as possible to the server (thin client). The more functionality you off-load to the server, the easier it is to distribute, deploy, and manage the application; however, keeping more functionality on the client can make for a better perceived user experience.

Web Components

Java EE web components are either servlets or pages created using JSP technology (JSP pages) and/or JavaServer Faces technology.Servletsare Java programming language classes that dynamically process requests and construct responses.JSP pagesare text-based documents that execute as servlets but allow a more natural approach to creating static content.JavaServer Faces

technology builds on servlets and JSP technology and provides a user interface component framework for web applications.

Web Tier

Business Tier

Client Tier

Java EE Server > Web Browser, Web Pages,

Applets, and Optional JavaBeans Components > Application Client and

Optional JavaBeans Components

(47)

Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the Java EE specification. Server-side utility classes can also be bundled with web components and, like HTML pages, are not considered web components.

As shown inFigure 1–3, the web tier, like the client tier, might include a JavaBeans component to manage the user input and send that input to enterprise beans running in the business tier for processing.

Business Components

Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier.

Figure 1–4shows how an enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.

Web Tier

Business Tier

Client Tier

Java EE Server > Web Browser, Web Pages,

Applets, and Optional JavaBeans Components > Application Client and

Optional JavaBeans Components

JavaBeans Components

(Optional)

JSP Pages Servlets

FIGURE 1–3 Web Tier and Java EE Applications

Referências

Documentos relacionados

b) nas linguiças fabricadas com nitrito e nitrato de sódio. Os últimos dados da Pesquisa de Orçamentos Familiares, realizada entre 2002 e 2003 pelo IBGE, mostram que 40,6%

A participação na escola refere-se à participação em atividades no seio da instituição, que no entanto, não estão diretamente relacionadas com as aulas de Educação Física,

Por ampliar os elementos de uma autonomia individual, por compreendê-la com inter- subjetivamente formada, a teoria da justiça pelo reconhecimento deve debruçar-se sobre as

É importante destacar que as práticas de Gestão do Conhecimento (GC) precisam ser vistas pelos gestores como mecanismos para auxiliá-los a alcançar suas metas

A infestação da praga foi medida mediante a contagem de castanhas com orificio de saída do adulto, aberto pela larva no final do seu desenvolvimento, na parte distal da castanha,

Tabela 6 – Equações de regressão dos fatores para determinação da produção de soja em função de adubação, época de plantio e anos de cultivo da área, e coeficiente

Assunto Problemático/ De que seja mais digna a Rosa: de alegria, quando nasce, ou de lástima, quando morre?/ Romance/ do Padre Eusébio de Matos, irmão do célebre Poeta Gregório de

Tendo em conta este factor de risco, deu-se preferência à seleção de cabras com condição corporal excessiva no primeiro trimestre de gestação (para além de diagnóstico