ias dev guide

Upload: mihaela-motas

Post on 07-Apr-2018

244 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 iAS Dev Guide

    1/146

  • 8/3/2019 iAS Dev Guide

    2/146

    Oracle9i App lication Server App lication Develop ers Guid e, Release 2 (9.0.2)

    Part No. A95101-01

    Copyr ight 2002, Oracle Corpora tion. All rights reserved .

    The Programs (which includ e both the software and documentation) contain propr ietary information ofOracle Corporation; they are provid ed u nd er a license agreement containing restrictions on use anddisclosure and are also protected by copyright, patent and other intellectual and industrial propertylaws. Reverse engineering, d isassemb ly or decomp ilation of the Progra ms, except to th e extent requ iredto obtain interoperability with other ind epend ently created softw are or as specified by law, is prohibited.

    The inform ation contained in this docu men t is subject to chan ge withou t notice. If you find any p roblems

    in the d ocumentation, please report them to us in writing. Oracle Corporation d oes not warran t that thisdocum ent is error-free. Except as m ay be expressly perm itted in you r license agreement for th esePrograms, no part of these Programs may be reprodu ced or tran smitted in any form or by any m eans,electronic or mechanical, for any pu rp ose, withou t the express written p ermission of Oracle Corpora tion.

    If the Program s are delivered to the U.S. Governmen t or anyon e licensing or using the p rogram s onbehalf of the U.S. Governm ent, the following n otice is app licable:

    Restricted Rights N otice Program s delivered sub ject to the DOD FAR Su pp lement are "comm ercialcomputer software" and use, duplication, and disclosure of the Programs, including documentation,shall be su bject to the licensing restrictions set forth in the ap plicable Oracle license agreem ent.

    Otherw ise, Program s delivered su bject to the Federal Acquisition Regulations are "restricted comp utersoftware" and u se, dup lication, and disclosure of the Program s shall be subject to the restrictions in FAR52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500Oracle Parkway, Redwood City, CA 94065.

    The Program s are not intend ed for u se in any nu clear, aviation, mass transit, medical, or other inh erentlydan gerou s app lications. It shall be the licensee's responsibility to take all app ropr iate fail-safe, backup ,redu nd ancy, and other m easures to ensure the safe use of such applications if the Programs are used forsuch purposes, and Oracle Corporation disclaims liability for any damages caused by such use of thePrograms.

    Oracle is a registered tra dem ark, and OracleMetaLink, Ora cle Store, Oracle9i, Oracle9iAS Discoverer, andPL/ SQL are trademarks or registered trad emarks of Oracle Corporation. Other names may betrademarks of their respective owners.

  • 8/3/2019 iAS Dev Guide

    3/146

    iii

    Contents

    1 Creating Applications: Overview

    1.1 Overview of Oracle9iAS....................................................................................................... 1-2

    1.1.1 J2EE .................................................................................................................................. 1-2

    1.1.2 Enterprise Portals ........................................................................................................... 1-2

    1.1.3 Wireless Support ............................................................................................................ 1-3

    1.2 Development Step s ............................................................................................................... 1-5

    1.3 Development Tools ............................................................................................................... 1-6

    1.4 What This Gu ide Covers and Does Not Cover ................................................................. 1-6

    2 The Sample Application

    2.1 Requ irements for the Sam ple Ap plication ........................................................................ 2-22.2 Screenshots of the Sample Ap plicat ion .............................................................................. 2-3

    2.3 Database Schema ................................................................................................................... 2-7

    3 Application Design

    3.1 Design Goals .......................................................................................................................... 3-2

    3.2 Chaining Pages ...................................................................................................................... 3-3

    3.3 Using Mod el-View -Controller (MVC) ............................................................................... 3-4

    3.3.1 MVC Diagram ................................................................................................................. 3-4

    3.3.2 Controller ........................................................................................................................ 3-6

    3.3.3 Model (Business Logic) ................................................................................................. 3-6

    3.3.4 View ................................................................................................................................. 3-7

    http://comments_template.pdf/http://comments_template.pdf/
  • 8/3/2019 iAS Dev Guide

    4/146

    iv

    4 Implementing Business Logic

    4.1 Objects Need ed by the Application .................................................................................... 4-2

    4.2 Other Op tions Con sid ered But N ot Taken ........................................................................ 4-3

    4.2.1 Con d itions that Favor Using EJBs................................................................................ 4-3

    4.2.2 Conditions that Favor Using Servlets.......................................................................... 4-3

    4.2.3 Cond itions tha t Favor Usin g N orm al Java Objects ................................................... 4-3

    4.3 Controller ................................................................................................................................ 4-5

    4.4 Action Handlers..................................................................................................................... 4-84.5 Employee Data (Entity Bean)............................................................................................... 4-9

    4.5.1 Hom e Interface ............................................................................................................. 4-10

    4.5.2 Remote Interface........................................................................................................... 4-11

    4.5.3 Persist ence ..................................................................................................................... 4-12

    4.5.4 Load Meth od ................................................................................................................. 4-12

    4.5.5 EmployeeMod el Class ................................................................................................. 4-12

    4.5.6 Data Access Object for Employee Bean ..................................................................... 4-144.5.6.1 Interface .................................................................................................................. 4-14

    4.5.6.2 Implem en tation ..................................................................................................... 4-14

    4.5.6.3 Load Meth od .......................................................................................................... 4-16

    4.6 Benefit Data (Stateless Session Bean )................................................................................ 4-18

    4.6.1 Hom e Interface ............................................................................................................. 4-18

    4.6.2 Remote Interface........................................................................................................... 4-19

    4.6.3 Benefit Deta ils ............................................................................................................... 4-204.7 EmployeeManager (Stateless Session Bean).................................................................... 4-21

    4.7.1 Hom e Interface ............................................................................................................. 4-22

    4.7.2 Remote Interface........................................................................................................... 4-23

    4.8 Utility Classes....................................................................................................................... 4-25

    5 Creating Presentation Pages

    5.1 HTML Files ............................................................................................................................. 5-1

    5.2 Serv let s .................................................................................................................................... 5-2

    5.2.1 Au tomatic Compilat ion of Serv lets ............................................................................. 5-2

    5.2.2 Exam ple ........................................................................................................................... 5-3

    5.2.3 Example: Calling an EJB................................................................................................ 5-3

    5.3 JSPs........................................................................................................................................... 5-5

    5.3.1 Tag Librar ies ................................................................................................................... 5-5

  • 8/3/2019 iAS Dev Guide

    5/146

    v

    5.3.2 Min imal Cod ing in JSPs ................................................................................................ 5-5

    5.3.3 Mu ltip le Client Typ es .................................................................................................... 5-6

    6 Interaction Between Clients and Business Logic Objects

    6.1 Clien t Interface to Business Tier Objects ............................................................................ 6-2

    6.2 Qu ery Employee Op erat ion ................................................................................................. 6-3

    6.2.1 High-Level Sequ ence ..................................................................................................... 6-3

    6.2.2 Qu erying the Database and Retriev ing Data ............................................................. 6-46.2.3 find ByPrim aryKey Method .......................................................................................... 6-6

    6.2.4 Getting Benefit Data....................................................................................................... 6-7

    6.3 Ad d and Remove Benefit Op erations ................................................................................ 6-9

    6.4 Ad d Benefit Operation ....................................................................................................... 6-10

    6.4.1 High-Level Sequ ence of Events.................................................................................. 6-10

    6.4.2 Gettin g Benefits That th e User Can Ad d .................................................................. 6-11

    6.4.3 Up dating th e Database ................................................................................................ 6-126.5 Removing Benefit Op eration ............................................................................................. 6-14

    6.5.1 High-Level Sequ ence of Events.................................................................................. 6-14

    6.5.2 Getting Benefits That the User Can Remove............................................................ 6-15

    6.5.3 Up dating th e Database ................................................................................................ 6-16

    7 Supporting Wireless Clients

    7.1 Changes You Need To Make To Your Ap plication .......................................................... 7-2

    7.2 Presentation Data for Wireless Clients............................................................................... 7-3

    7.2.1 Screen s for the Wireless Ap plication ........................................................................... 7-3

    7.2.2 Differences Between the Wireless and the Browser Application............................ 7-5

    7.3 Deciding Where to Pu t the Presen tation Data for Wireless Clients ............................... 7-7

    7.3.1 Determining the Origin of a Request .......................................................................... 7-7

    7.3.2 Com bining Presentation Data in the Sam e JSP File .................................................. 7-87.3.3 Separatin g Presentat ion Data into Separate Files.................................................... 7-10

    7.4 Head er Information in JSP Files for Wireless Clients .................................................... 7-12

    7.4.1 Sett ing th e XML Typ e .................................................................................................. 7-12

    7.4.2 Setting the Con ten t Typ e............................................................................................. 7-12

    7.5 Operation Details................................................................................................................. 7-13

    7.5.1 Qu ery Op erat ion .......................................................................................................... 7-13

    7.5.2 qu eryEmployeeWireless.jsp ....................................................................................... 7-15

  • 8/3/2019 iAS Dev Guide

    6/146

    vi

    7.5.3 Add and Remove Benefits Operations...................................................................... 7-16

    7.6 Accessing th e Ap plication .................................................................................................. 7-187.6.1 Using a Simulator ......................................................................................................... 7-18

    7.6.2 Using an Actual Wireless Client ................................................................................ 7-18

    8 Adding Web Cache to the Application

    8.1 Choosing Which Pages to Cache ......................................................................................... 8-2

    8.2 Analyzin g the Ap plication ................................................................................................... 8-3

    8.2.1 Specify ing the Pages to Cach e ...................................................................................... 8-3

    8.2.2 Invalid at ing Pages .......................................................................................................... 8-4

    8.2.3 Setting up Triggers on the Underlying Tables ........................................................... 8-7

    9 Running in a Portal Framework

    9.1 How Portal Processes Requ ests ........................................................................................... 9-2

    9.2 Screenshots of the App lication in a Portal ......................................................................... 9-3

    9.3 Changes You Need to Make to the Application ............................................................... 9-7

    9.3.1 Set up a Provider an d a Portal Page ............................................................................ 9-7

    9.3.2 Edit the Ap plication ....................................................................................................... 9-8

    9.4 Up date the Links Betw een Pages With in a Por tlet ........................................................... 9-9

    9.4.1 The param eterizeLink Meth od ..................................................................................... 9-9

    9.4.2 The next_p age Parameter ............................................................................................ 9-10

    9.4.3 Link ing to the ID Page ................................................................................................. 9-11

    9.5 Use include instead of the forw ard Method .................................................................... 9-12

    9.6 Protect Parameter Nam es ................................................................................................... 9-13

    9.6.1 Retrieving Values ......................................................................................................... 9-14

    9.6.2 Sett ing Values ............................................................................................................... 9-14

    9.7 Make All Path s Absolute .................................................................................................... 9-15

    9.7.1 and Tags .................................................................................................... 9-159.7.2 Tag.................................................................................................................... 9-15

    10 Enhancements to the Application

    10.1 Ad ding Security Features ................................................................................................... 10-1

    10.2 Publishing the Application as a Web Service.................................................................. 10-1

  • 8/3/2019 iAS Dev Guide

    7/146

    vii

    A Configuration Files

    A.1 serv er .xml ............................................................................................................................... A-1

    A.2 defau lt-w eb-site.xml ............................................................................................................. A-2

    A.3 data-sources.xml.................................................................................................................... A-2

  • 8/3/2019 iAS Dev Guide

    8/146

    viii

  • 8/3/2019 iAS Dev Guide

    9/146

    ix

    Send Us Your Comments

    Oracle9i Application Server Application Developers Guide, Release 2 (9.0.2)

    Part No. A95101-01

    Oracle Corporation w elcomes your comm ents and su ggestions on the quality and u sefulness of this

    docum ent. Your inp ut is an imp ortant p art of the information u sed for revision.

    s Did you find any errors?

    s Is the information clearly presented ?

    s Do you n eed m ore information? If so, where?

    s Are the examples correct? Do you need more examp les?

    s What features did you like most?

    If you find an y errors or have any other su ggestions for improvement, please indicate the document

    title and par t nu mber, and th e chapter, section, and page n um ber (if available). You can send com-

    men ts to us in the following w ays:

    s Electronic ma il: iasd [email protected]

    s FAX: 650-506-7407 Attn : Oracle9i Application Server Documen tation Manager

    s Postal service:

    Oracle Corporation

    Oracle9i App lication Server Documentation

    500 Oracle Parkway, M/ S 2op3

    Redw ood Shores, CA 94065USA

    If you w ould like a reply, please give your name, add ress, telephone n um ber, and (optionally) elec-

    tronic mail add ress.

    If you have p roblems w ith the software, please contact your local Oracle Supp ort Services.

  • 8/3/2019 iAS Dev Guide

    10/146

    x

  • 8/3/2019 iAS Dev Guide

    11/146

    xi

    Preface

    Oracle9i App lication Server Ap plication Developer s Guid e describes how to create

    mod ular, extensible, and maintainable J2EE app lications. It highlights h ow to

    structure you r app lications so that you get the maximu m benefits from the features

    in O racle9i App lication Server. You sh ould use th is guide along with the OC4J

    Users Guide.This preface contains these top ics:

    s Intend ed Aud ience

    s Documentation Accessibility

    s Related Docum entation

    s Conventions

  • 8/3/2019 iAS Dev Guide

    12/146

    xii

    Intended AudienceOracle9i App lication Server Application Developer s Guide is intend ed for

    developers w ho perform the following tasks:

    s Design and create J2EE (with EJB, JSP, and servlets) ap plications

    s Enhance app lications to sup port w ireless clients

    s Enable applications to run in a portal framew ork

    To use this document, you need to be familiar with Java and have some exposure to

    J2EE techn ology.

    Documentation AccessibilityOur goal is to make Oracle produ cts, services, and sup porting d ocumentation

    accessible, with good usability, to the disabled commu nity. To tha t end , our

    docum entation includes features that make information available to users of

    assistive technology. This documen tation is available in HTML format, and containsmarkup to facilitate access by the d isabled commu nity. Stand ards will continue to

    evolve over time, and Oracle Corporation is actively engaged w ith other

    market-leading technology vendors to ad dress technical obstacles so that ou r

    docum entation can be accessible to all of our custom ers. For ad ditional information,

    visit the Oracle Accessibility Program Web site at

    http://www.oracle.com/accessibility/

    Accessibility of Code Examples in Documentation JAWS, a Wind ows screen

    reader, may n ot always correctly read the code examp les in th is docum ent. The

    conventions for writing code require that closing braces should ap pear on an

    otherw ise empty line; how ever, JAWS may not always read a line of text that

    consists solely of a bracket or brace.

    Accessibility of Links to External Web Sites in Documentation This

    docum entation m ay contain links to Web sites of other comp anies or organizations

    that Oracle Corporat ion does not ow n or control. Oracle Corporation neither

    evaluates n or m akes any representations regard ing the accessibility of these Web

    sites.

  • 8/3/2019 iAS Dev Guide

    13/146

    xiii

    Related DocumentationFor more in formation, see these Oracle resources:

    s Oracle9i A pplication Server Concepts

    s Oracle9i App lication Server Docum entation Library

    s Oracle9i App lication Server Platform-Specific Docum entation on Oracle9i

    App lication Server Disk 1

    In Nor th Am erica, printed docum entation is available for sale in the Oracle Store at

    http://oraclestore.oracle.com/

    Custom ers in Europe, the Mid dle East, and Africa (EMEA) can p urchase

    documentation from

    http://www.oraclebookshop.com/

    Other custom ers can contact their Oracle representative to purchase p rinted

    documentation.

    To dow nload free release notes, installation docum entation, wh ite papers, or other

    collateral, please visit the Oracle Technology Network (OTN). You must register

    online before using OTN; registration is free and can be don e at

    http://otn.oracle.com/admin/account/membership.html

    If you already have a username and password for OTN, then you can go directly to

    the d ocumen tation section of the OTN Web site at

    http://otn.oracle.com/docs/index.htm

    ConventionsThis section describes the conventions u sed in th e text and code examples of this

    docum entation set. It describes:

    s Convention s in Text

    s Conventions in Code Examples

    s Conventions for Microsoft Window s Operating Systems

  • 8/3/2019 iAS Dev Guide

    14/146

    xiv

    Conventions in Text

    We use va rious conventions in text to help you more qu ickly identify special terms.The following table describes those conventions an d p rovides examples of their u se.

    Convention Meaning Example

    Bold Bold typ eface indicates terms th at aredefined in the text or terms that app ear ina glossary, or both .

    When you sp ecify this clause, you create anindex-organized table.

    Italics Italic typeface indicates book titles oremphasis.

    Oracle9i Database Concepts

    Ensure that the recovery catalog and targetdatabase do notreside on the same d isk.

    UPPERCASE

    monospace

    (fixed-width)

    font

    Upp ercase mon ospace typeface indicateselements sup plied by the system. Suchelements include parameters, privileges,datatypes, RMAN keywords, SQLkeywords, SQL*Plus or u tility command s,

    packages and m ethods, as well assystem-supp lied column names, databaseobjects and structu res, usernames, androles.

    You can specify this clause only for a NUMBERcolumn.

    You can back up the da tabase by using theBACKUP command.

    Query theTABLE_NAME

    colum n in theUSER_

    TABLES data dictionary view.

    Use the DBMS_STATS.GENERATE_STATSprocedure.

    lowercase

    monospace

    (fixed-width)

    font

    Lowercase monospace typeface indicatesexecutab les, filenames, directory nam es,and sample user-supplied elements. Suchelements include comp uter and databasenam es, net service names, and connect

    identifiers, as well as user-sup plieddatabase objects and structures, colum nnam es, packages and classes, usern amesand roles, program units, and param etervalues.

    Note: Some programmatic elements use amixture of UPPERCASE and lowercase.Enter these elements as show n.

    Enter sqlplus to op en SQL*Plus.

    The password is specified in the orapwd file.

    Back up the d atafiles and control files in the/disk1/oracle/dbs directory.

    The department_id, department_name,and location_id colum ns are in thehr.departments table.

    Set the QUERY_REWRITE_ENABLEDinitialization parameter to true.

    Connect as oe user.

    The JRepUtil class implements these

    methods.

    lowercase

    italic

    monospace

    (fixed-width)

    font

    Lowercase italic monosp ace fontrepresents placeholders or var iables.

    You can specify theparallel_clause.

    Run Uold_release.SQL where old_releaserefers to the release you installedprior to up grading.

  • 8/3/2019 iAS Dev Guide

    15/146

    xv

    Conventions in Code Examples

    Code examples illustrate SQL, PL/ SQL, SQL*Plus, or other comm and -linestatemen ts. They are displayed in a monosp ace (fixed-width) font and separated

    from n ormal text as shown in this examp le:

    SELECT username FROM dba_users WHERE username = MIGRATE;

    The following table describes typograph ic conventions used in code examples and

    provid es examples of their use.

    Convention Meaning Example

    [ ] Brackets enclose one or more optionalitems. Do not enter the brackets.

    DECIMAL (digits [ ,precision ])

    { } Braces enclose two or m ore items, one ofwh ich is required. Do not enter thebraces.

    {ENABLE | DISABLE}

    | A vertical bar represents a choice of twoor more op tions within brackets or braces.Enter one of the op tions. Do not enter thevertical bar.

    {ENABLE | DISABLE}

    [COMPRESS | NOCOMPRESS]

    ... Hor izontal ellipsis points ind icate either:

    s That we have omitted p arts of thecode that are not directly related tothe example

    s

    That you can repeat a p ortion of thecode

    CREATE TABLE ... AS subquery;

    SELECT col1, col2, ... , coln FROM

    employees;

    .

    .

    .

    Vertical ellipsis points indicate that wehave om itted several lines of code notd irectly related to the examp le.

    Other notation You must enter symbols other thanbrackets, braces, vertical bars, and ellipsispoints as shown.

    acctbal NUMBER(11,2);

    acct CONSTANT NUMBER(4) := 3;

    Italics Italicized text ind icates placeholders orvariables for wh ich you mu st supp lyparticular values.

    CONNECT SYSTEM/system_password

    DB_NAME = database_name

  • 8/3/2019 iAS Dev Guide

    16/146

    xvi

    Conventions for Microsoft Windows Operating Systems

    The following table describes conventions for Microsoft Wind ows operating

    systems and provides examples of their use.

    UPPERCASE Upp ercase typeface indicates elemen tssup plied by the system. We show theseterms in u pp ercase in order to d istinguishthem from term s you d efine. Unless termsapp ear in brackets, enter them in theorder and w ith the spelling shown.How ever, because these terms are notcase sensitive, you can enter th em inlowercase.

    SELECT last_name, employee_id FROM

    employees;

    SELECT * FROM USER_TABLES;

    DROP TABLE hr.employees;

    lowercase Lowercase typeface ind icatesprogramm atic elements that you supp ly.For example, lowercase ind icates nam esof tables, columns, or files.

    Note: Some programmatic elements use amixture of UPPERCASE and lowercase.Enter these elements as show n.

    SELECT last_name, employee_id FROM

    employees;

    sqlplus hr/hr

    CREATE USER mjones IDENTIFIED BY ty3MU9;

    Convention Meaning Example

    Choose Start > How to start a program. To start the Oracle Database Configuration

    Assistant, choose Start > Progra ms > Oracle -HOME_NAME> Configuration and MigrationTools > Database Configuration Assistant.

    File and directorynames

    File and d irectory nam es are not casesensitive. The following special charactersare not allowed: left angle bracket (), colon (:), doublequotation marks ("), slash (/ ), pipe (| ),and dash (-). The special character

    backslash (\ ) is treated as an elementseparator, even when it app ears in quotes.If the file name begins with \ \ , thenWindows assumes it uses the UniversalNam ing Convention.

    c:\winnt"\"system32 is the same asC:\WINNT\SYSTEM32

    Convention Meaning Example

  • 8/3/2019 iAS Dev Guide

    17/146

    xvii

    C:\> Represents the Windows comm andpromp t of the current hard disk drive.The escape character in a comm andprom pt is the caret ( ). Your p romptreflects the subdirectory in which you areworking. Referred to as the command

    promptin this manual.

    C:\oracle\oradata>

    The backslash (\ ) special character is

    sometimes required as an escapecharacter for the dou ble quotation m ark(") special character at the Window scomm and p rompt. Parentheses and thesingle quotation ma rk () do not requirean escape character. Refer to yourWindows operating systemdocumentation for more information onescape and special characters.

    C:\>exp scott/tiger TABLES=emp

    QUERY=\"WHERE job=SALESMAN andsal

  • 8/3/2019 iAS Dev Guide

    18/146

    xviii

    ORACLE_HOMEand ORACLE_BASE

    In releases prior to Oracle8i release 8.1.3,when you installed Oracle components,all subd irectories were located u nd er atop level ORACLE_HOMEdirectory that bydefault used one of the following names:

    s C:\orant for Windows N T

    s C:\orawin95 for Wind ows 95

    s C:\orawin98 for Wind ows 98

    This release comp lies with Optim alFlexible Architecture (OFA) guidelines.All subd irectories are not und er a toplevel ORACLE_HOMEdirectory. There is atop level directory called ORACLE_BASEthat by d efault is C:\oracle. If youinstall Oracle9i release 1 (9.0.1) on acomp uter w ith no other Oracle softwareinstalled , then the default setting for thefirst Oracle home d irectory isC:\oracle\ora90. The Oracle hom edirectory is located directly und erORACLE_BASE.

    All directory path examples in this guidefollow OFA conven tions.

    Refer to Oracle9i Database Getting Startingfor Windows for additional information

    abou t OFA compliances and forinformation abou t installing Oracleproducts in non-OFA compliantdirectories.

    Go to the ORACLE_BASE\ORACLE_HOME\rdbms\admin directory.

    Convention Meaning Example

  • 8/3/2019 iAS Dev Guide

    19/146

    Creating Applications: Overview 1-1

    1Creating Applications: Overview

    When you create app lications to be deployed on Oracle9i Application Server, you

    might th ink of different w ays to implemen t a featu re. This guide wa lks you through

    the design and imp lementation of a sample app lication, and in the process of doing

    so, it discusses the available options for each featu re and the ad vantages and

    disadvantages of each option.

    The resulting app lication is mod ular and extensible: you can easily add features,

    add different client typ es (including wireless devices), and change the

    imp lementation of a feature with minima l imp act on other features.

    The samp le app lication u sed in this gu ide is called "Employee Benefit Ap plication".

    It enables users to view da ta such as employee nam e, phone, email, and job ID.

    Users can also ad d or remove their benefit elections. The app lication retrieves and

    up dates data in an Oracle database.

    The samp le app lication makes use of many d ifferent technologies, includ ing

    JavaServer Pages, serv lets, Enterprise JavaBeans, JDBC, portals, w ireless devices,

    web cache, web serv ices, JNDI, and JAAS.

    Contents of this chapter:

    s Section 1.1, "Overview of Oracle9iAS"

    s Section 1.2, "Developm ent Steps"

    s Section 1.3, "Develop ment Tools"

    s Section 1.4, "What This Guide Covers and Does Not Cover"

  • 8/3/2019 iAS Dev Guide

    20/146

  • 8/3/2019 iAS Dev Guide

    21/146

    Overview of Oracle9iAS

    Creating Applications: Overview 1-3

    they can see only the app lications to w hich they have access with single sign-on

    capabilities. These applications, when d isplayed w ithin a porta l framework , arecalled portlets.

    Figure 11 show s a picture of a portal.

    Figure 11 A portal page

    1.1.3 Wireless SupportBrowser clients d o their rendering based on H TML tags, and th ere is more or less a

    stand ard set of tags and attributes that you can u se. Wireless clients, on the other

  • 8/3/2019 iAS Dev Guide

    22/146

    Overview of Oracle9iAS

    1-4 Oracle9i Application Server Application Developers Guide

    hand , und erstand different sets of tags and attributes, depending on the wireless

    dev ice, and speak d ifferent p rotocols.

    To m ake it easy for app lication d evelopers, the w ireless feature in Oracle9iAS comes

    with ad aptor s and transformers. This enables you to w rite your ap plication once,

    and provid e access to it from any wireless device. The way th is works is that you

    wr ite the presentation data in XML according to a stand ard DTD (docum ent type

    definition), and the adaptors convert the XML on the fly to the markup language

    preferred by the client.

    You can w rite your app lication such that it sup ports both brow sers and w irelessdevices. Your application can check if a request is coming from a w ireless client and

    return the approp riate response (HTML or XML). The sample application show s

    how to do th at. See Chap ter 7, "Sup port ing Wireless Clients" for details.

    Figure 12 show s the Employee Benefit application running on a cell phone:

    Figure 12 An application running on a cell phone

    1. Enter employee ID and click OK. 2. View employee information.

  • 8/3/2019 iAS Dev Guide

    23/146

    Development Steps

    Creating Applications: Overview 1-5

    1.2 Development StepsDesigning and develop ing an ap plication w ith all these technologies can be a little

    overw helming. Here are some h igh-level steps to guide you (later chap ters in this

    book provide the details):

    1. Determine application requirements.

    Be sure to separate the p resentation (or client) tier requiremen ts from the

    business logic tier requirements. Separating the requ irements by tier helps you

    design you r app lication in a modu lar fashion. Modu larity promotes a clean

    separation of functionality and enables you to reuse, up date, or replace

    mod ules without affecting the rest of the application.

    See Section 2.1, "Requirements for the Sample App lication" for details.

    2. In the bu siness logic tier, determine wh at objects you need and the interfaces of

    these objects.

    It helps to draw a sketch of the d esign based on th e interfaces. Also determine

    how the client tier can invoke m ethods in the objects.

    When you determine wh at objects you need, you h ave many im plementation

    choices. For examp le, you can u se servlets, JavaBeans, Enterp rise JavaBeans, or

    plain Java classes to imp lement you r business logic.

    See Chap ter 4, "Implementing Business Logic" for details.

    3. In the client tier, create the presentat ion d ata for th e client.

    The presentation data determine how the app lication looks to the users.Typ ically, the p resenta tion d ata is in H TML (for browsers) or XML (for w ireless

    devices). The H TML or XML tags can come from static files, JSPs, or other Java

    classes.

    JSPs and other Java classes can outp ut th e presentation d ata programmatically.

    In JSP files, you embed command s to invoke m ethods on th e Java objects that

    imp lement you r business logic. You can then d isplay the values that the

    methods return.See Chap ter 5, "Creating Presentation Pages" for d etails.

    4. Implemen t the business logic.

    You can d o th is with EJBs, servlets, or other Java classes.

    See Chap ter 4, "Implementing Business Logic" for details.

    5. Package, dep loy, and run your ap plication.

    D l t T l

  • 8/3/2019 iAS Dev Guide

    24/146

    Development Tools

    1-6 Oracle9i Application Server Application Developers Guide

    1.3 Development ToolsTo create ap plications for Oracle9iAS, you can u se text editors such as emacs or vi,or you can use IDEs (integrated d evelopmen t environmen t).

    If you use a text editor, you also need additional tools such as a Java comp iler (for

    example,javac), a Java archive tool (for exam ple,jar), and a packaging tool so that

    you can compile you r files and build JAR and EAR files.

    If you use IDEs, they can au tomate the tasks listed above for you . Oracle provid es

    an IDE called Oracle9i JDeveloper. JDeveloper has sup port for each stage in the

    developm ent lifecycle: it contains UML modelling an d generation tools, debuggingtools, profiling tools, and tun ing tools.

    JDeveloper is closely integrated with Oracle9iAS: you can d eploy ap plications on

    Oracle9iAS from JDeveloper.

    1.4 What This Guide Covers and Does Not CoverThis guide show s a complete ap plication, clients (browsers and wireless devices),and database schem a. It describes the logic behind the application d esign.

    It also shows how to deploy/ configure the app lication.

    It does not d escribe the details for the APIs tha t the ap plication u ses. For that

    information, refer to the Oracle9iAS J2EE Users Guide.

    This guide a ssum es the read er has some concept of servlets, JSPs, portals, web

    services, wireless d evices, and introdu ctory know ledge of EJBs. If you need moreinformation on these top ics, see the Oracle9iAS library for a list of books.

    To read the Java sp ecifications, see:

    http://java.sun.com

  • 8/3/2019 iAS Dev Guide

    25/146

    The Sample Application 2-1

    2The Sample Application

    This chapter describes the samp le application, "Employee Benefit App lication",

    used in this guide.

    Contents of this chapter:

    s Section 2.1, "Requirements for th e Sample Ap plication"

    s Section 2.2, "Screensh ots of the Samp le Application"

    s Section 2.3, "Database Schema"

    Requirements for the Sample Application

  • 8/3/2019 iAS Dev Guide

    26/146

    Requirements for the Sample Application

    2-2 Oracle9i Application Server Application Developers Guide

    2.1 Requirements for the Sample Application

    The Employee Benefit ap plication enables users to v iew em ployee information(such as first name, last name, email, and phone n um ber), and ad d and remove

    benefits. A typical user of the app lication is an em ployee who m anages benefits for

    other employees in a comp any.

    The fun ctional requirements for the sample ap plication are:

    s Display d ata from the employees, employee_benefit_items, and benefits tables

    on the Info page (Figure 21). The database schema for these tables is listed in

    Section 24, "Database schema".

    s Enable the user to add benefits.

    s Enable the user to rem ove benefits.

    Miscellaneous:

    s App lication mu st be able to run w ithin a portal.

    Clients for th e application:

    s Web brow sers

    s Wireless clients (mobile phones and PDAs)

    Screenshots of the Sample Application

  • 8/3/2019 iAS Dev Guide

    27/146

    Screenshots of the Sample Application

    The Sample Application 2-3

    2.2 Screenshots of the Sample ApplicationWhen the user invokes the app lication, the first page prom pts the user to enter anemp loyee ID (Figure 21).

    When the user clicks the Query Emp loyee button, the app lication queries the

    database for the specified employee ID. If found , the app lication d isplays

    information for that emp loyee, includ ing wh ich benefits the emp loyee has curren tly

    elected (Figure 21).

    If the emp loyee ID does not match an emp loyee, the application d isplays an error

    page (Figure 23).

    On the Info page, the user can add or remove benefits by selecting the Ad d or

    Remove Benefit link. The ap plication then d isplays the Ad d or Remove Benefits

    page (Figure 22). The user selects wh ich benefits to ad d or remove, and clicks the

    Ad d Selected Benefits or Remove Selected Benefits bu tton . If successful, the

    app lication displays the Success page, and the u ser can click the "Query th e Same

    Employee" link to see the u pd ated benefits.

    For screen shots of the ap plication ru nning on a wireless device, see Chapter 7,

    "Supporting Wireless Clients".

    Screenshots of the Sample Application

  • 8/3/2019 iAS Dev Guide

    28/146

    p pp

    2-4 Oracle9i Application Server Application Developers Guide

    Figure 21 ID page and Info page

    ID page

    Info page

    Displays the Add Benefits page

    Displays the Remove Benefits page

    Screenshots of the Sample Application

  • 8/3/2019 iAS Dev Guide

    29/146

    The Sample Application 2-5

    Figure 22 Add Benefits Page, Remove Benefits Page, and Success Page

    Add Benefits page Remove Benefits page

    Success page

    Screenshots of the Sample Application

  • 8/3/2019 iAS Dev Guide

    30/146

    2-6 Oracle9i Application Server Application Developers Guide

    Figure 23 Error page

    Database Schema

  • 8/3/2019 iAS Dev Guide

    31/146

    The Sample Application 2-7

    2.3 Database SchemaThe Employee Benefit sam ple application u ses the common hr schema that comeswith Oracle9i database and Oracle9iAS Metadata Repository. The ap plication u ses

    th e hr.employees table, plu s two ad ditional tables (benefits an d employee_benefit_

    items) that you install. You install these tables in the d efault tablespace of the hr

    schema.

    The app lication retrieves data from all three tables, bu t up dates only the employee_

    benefit_items table.

    Figure 24 Database schema

    Table 21 Tables in the hr schema

    Table name Descriptionem ployees Contain s field s su ch as: em ployee_id , first_n am e, last_nam e,

    phon e, email, and dep artment.

    benefits Contains fields such as benefit_id , benefit_nam e, and benefit_description.

    employee_benefit_items Maps emp loyees with benefits. The table has fields such asemp loyee_id, emp loyee_id, and election_date. An emp loyee canhave m ultiple benefits. This is the table that th e app lication

    up dates wh en emp loyees up date their benefit elections.

    EMPLOYEES

    PK Employee_ID

    First_name

    Last_name

    Email

    Phone_number

    Hire_date

    Job_id

    Salary

    Commission_pct

    Manager_id

    Department_id

    BENEFITS

    PK Benefit_id

    Benefit_name

    Benefit_description

    EMPLOYEE_BENEFIT_ITEMS

    PK Employee_id

    PK Benefit_id

    Election_date

    Database Schema

  • 8/3/2019 iAS Dev Guide

    32/146

    2-8 Oracle9i Application Server Application Developers Guide

  • 8/3/2019 iAS Dev Guide

    33/146

    Application Design 3-1

    3Application Design

    There are several ways to d esign the architecture of the ap plication d escribed in

    Chap ter 2, "The Sample App lication". One way is to "chain" the pages, where page 1

    calls page 2, page 2 calls page3, and so on . Another w ay is to use th e

    mod el-view-controller (MVC) design p attern.

    Contents of this chapter:s Section 3.1, "Design Goals"

    s Section 3.2, "Chaining Pages"

    s Section 3.3, "Using Mod el-View-Controller (MVC)"

    Design Goals

  • 8/3/2019 iAS Dev Guide

    34/146

    3-2 Oracle9i Application Server Application Developers Guide

    3.1 Design Goals

    You w ant to design you r app lication such that changes to one part of theapp lication has m inimal or no impact on other parts. This enables you to:

    s Add features w ithout redesigning your app lication

    s Add n ew client typ es (such as w ireless devices)

    s Change client interfaces with m inimal impact to your business logic

    s Change business logic without changing presentation d ata

    s Change your d atabase schema or d ata source with m inimal imp act on your

    application

    Chaining Pages

  • 8/3/2019 iAS Dev Guide

    35/146

    Application Design 3-3

    3.2 Chaining Pages

    In the chaining p ages design, pages in the ap plication are linked sequentially. Page1 has a link that calls page 2, page 2 has a link tha t calls page 3, and so on.

    Graphically:

    Figure 31 Chaining pages

    Each p age can be generated differently. For examp le, the p age 1 can be a p lain

    HTML file, page 2 can be generated by a servlet, while page 3 can be generated by a

    JSP. The pages contain links or form elements (if the user n eeds to en ter some

    values) to enable the u ser to get to the n ext page. In an y case, the link to the n ext

    page is hard coded on each page. See Chap ter 5, "Creating Presentation Pages"for a

    d iscussion of generating H TML or other marku p langu age.

    Advan tages of this design are that it is straightforward and easy to und erstand.

    This design is man ageable for small applications that are u nlikely to get bigger or

    whose pages are un likely to change.

    Disadvan tages of this design are that there is no central point to han dle client

    requests and it is difficult to move p ages around . If pages get moved, added , or

    removed from the application, the app lication becomes less organized because you

    have to track down the code that one page calls and m ove it to another p age, or

    change depend encies so that a p age can be called from a d ifferent p age.

    page 1 page 2 page 3

    /myApp/page2 /myApp/page3

    Using Model-View-Controller (MVC)

  • 8/3/2019 iAS Dev Guide

    36/146

    3-4 Oracle9i Application Server Application Developers Guide

    3.3 Using Model-View-Controller (MVC)

    A better way of designing this app lication is to use the MVC(model-view-controller) design patt ern. MVC enables the ap plication to be

    extensible and m odu lar by separa ting the app lication into three par ts:

    s the business logic part, which implements data retrieval and manipulation

    s the user interface part , which is wh at the app lication users see

    s the controller part, wh ich rou tes requests to the prop er objects.

    By separating an ap plication into these pa rts, the MVC design p attern enables youto mod ify one part of the app lication without d isturbing the other par ts. This means

    that you can have multiple developers w orking on d ifferent par ts of the app lication

    at the same time withou t getting into each other s domain. Each developer know s

    the role that each part p lays in the app lication. For example, the user interface par t

    cannot contain any code that has to d o with business logic, and vice versa.

    MVC also makes it easy to transform th e app lication into a por tlet or to have

    wireless devices access the app lication.For more d etails on MVC, see:

    http://java.sun.com/j2ee/blueprints/design_patterns/model_view_controller/index.html

    3.3.1 MVC DiagramThe following figure shows a high-level structure of the sam ple ap plication. When

    the ap plication receives a request from a client, it processes the requ est in the

    following manner:

    1. The client sends a request, which is hand led by the controller.

    2. The controller determines the action specified by the request, and looks up the

    class for the action. The class mu st be a su bclass of the AbstractActionHand ler

    class.

    3. The controller creates an instance of the class and invokes a method on tha t

    instance.

    4. The instan ce processes the requ est. Typically, it forward s the requ est to a JSP

    page.

    5. The JSP p age gets an instance of the Enterprise JavaBean ap prop riate for the

    action and invokes the method to perform the action.

    6. The JSP page then extracts the data th at the method retu rned for presentation.

    Using Model-View-Controller (MVC)

  • 8/3/2019 iAS Dev Guide

    37/146

    Application Design 3-5

    Figure 32 Application architecture

    Client

    Request

    ResponseController Servlet

    ActionHandler Interface

    ActionHandler implementation

    AbstractActionHandler class

    Access EJB Remote EJB Home

    EJB Implementation

    Data Access Object interface

    Data Access Object implementation

    Database

    JSP Page

    Access

    Forward

    1

    2

    3 4

    5

    6

    VIEW

    MODEL

    CONTROLLER

    Using Model-View-Controller (MVC)

  • 8/3/2019 iAS Dev Guide

    38/146

    3-6 Oracle9i Application Server Application Developers Guide

    3.3.2 Controller

    The controller is the first object in the application that receives requests from clients.All requests for any p age in the application m ust first go through the controller.

    In the controller, you map each request type w ith a class to hand le the request. For

    example, the samp le app lication has the following map pings:

    The action is a qu ery string param eter passed to the controller. The controller gets

    the value of the action param eter to determine the type.

    When the controller receives a request, it looks up the value of the actionparameter, determines th e class for the requ est, creates an instan ce of the class, and

    sends the request to that instance.

    You can hardcode the map ping in th e controller code itself, or you can set up the

    controller to read the m app ing information from a da tabase or XML file. It is more

    flexible to use a database or XML file.

    By hav ing a controller as the first point of contact in you r ap plication, you can ad d

    functionality to your app lication easily. You just need to add a m app ing and writethe new classes to implemen t the new functionality.

    In the sam ple ap plication, the controller object is a servlet. The pages in the

    app lication have links to this servlet.

    Using the controller object frees you from "chaining" pages in you r ap plication,

    wh ere you have to keep track of which page calls which other pages, and ad ding or

    removing p ages can be a non-trivial task.

    3.3.3 Model (Business Logic)The mod el represents the objects that imp lement your business logic. The objects

    process client d ata and return a response. The mod el also includ es data from the

    database. Objects in the mod el can include Enterpr ise JavaBeans, JavaBeans, and

    regular Java classes. Views an d controllers invoke objects in th e model.

    Table 31 Mappings in the controller for the sample application

    Action Class

    queryEmployee empbft.mvc.handler.QueryEmployee

    ad dBen efitToEm ployee em pbft.m vc.hand ler.Ad dBen efitToEm ployee

    removeBenefitFromEmployee empbft.mvc.handler.RemoveBenefitFromEmployee

    Using Model-View-Controller (MVC)

  • 8/3/2019 iAS Dev Guide

    39/146

    Application Design 3-7

    After the controller has read the request, objects in the mod el perform all the actual

    work in p rocessing the requ est. For examp le, the objects can extract values from the

    query string and validate the request, authenticate the client, begin a transaction,and query d atabases. In the sample app lication, the EmployeeManager session

    bean calls the Employee entity bean to query the da tabase and get information for

    an em ployee.

    Although it is tempting to en code presentation d ata in you r business logic, it is a

    better pr actice to separate the p resentation data into its own file. For example, if you

    write the presentation d ata in a JSP file, you can ed it the HTML marku p in th e file

    or change the format of the data w ithout chang ing the mod el code. The page canthen format the data according ly. JSP files do not care how th e methods get their

    data.

    Typ ically, objects in th e mod el read and up da te data in d atabases. If your

    app lication accesses databases, consider using DAO (data access objects) to separa te

    the d atabase access portion of your ap plication from the rest of the mod el. This

    enables you to isolate the SQL statements that you send to the database.

    Using DAOs gives you th e flexibility to chan ge your d ata sou rce. If you up da teyour database (for example, if you rename tables in the d atabase or change the

    structure of tables in the database), you can upd ate your SQL statemen ts in the data

    access objects withou t changing the rest of you r application.

    The sample application u ses a DAO to connect to the database. The DAO sets up a

    connection to the d atabase, executes the required SQL statemen ts on the d atabase,

    and returns the data.

    For add itional information on h ow to create a "clean" model, you migh t want toread th e J2EE bluep rints page and the Design Pattern s Catalog page on th e Sun site:

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

    http://java.sun.com/j2ee/blueprints/design_patterns/catalog.html

    3.3.4 ViewThe view includes presentation data such as HTML tags along with business data

    returned by the mod el. The presentation data and the business data are sent to the

    client in response to a request. The HTML tags usually have d ata and form elements

    (such as text fields and but tons) that the u ser can interact with, as well as other

    presentation elements.

    The presentation data and the business data should come from different sources.

    The business data should come from the mod el, and th e presentation d ata should

    Using Model-View-Controller (MVC)

  • 8/3/2019 iAS Dev Guide

    40/146

    3-8 Oracle9i Application Server Application Developers Guide

    come from JSP files. This w ay, you h ave a sep aration betw een p resentation and

    business data.

    One benefit of coding th e business and p resentation data separately is that it makes

    it easy to extend the ap plication to su pp ort d ifferent client typ es. For example, you

    might n eed to extend you r application to sup port w ireless devices. Wireless devices

    read WML or other markup language, depend ing on the d evice. If you embed you r

    presentation d ata in your business logic, it would be difficult to track which tag is

    for which client typ e. With the separation, you can reu se the same business objects

    with new presentation data.

    In addition, new clients of the app lication might n ot even be grap hical at all. Theymight n ot be interested in getting display tags. They m ight only be interested in

    getting a result, which they can p rocess how ever they like.

    The files for the presentation data should not contain any business logic code, other

    than invoking objects on the m odel side of the application. This enables you to

    change the implementation of the business logic and database schem a withou t

    mod ifying the client code.

    In the sam ple ap plication, client types includ e browsers, different typ es of wirelessdevices, non -web clients (such as other applications), and SOAP clients. You can

    add clients or change how the da ta is presented to the clients just by changing th e

    "view." The data can be HTML, WML, or any other markup language.

    In the sam ple ap plication, all the p resentation cod e is in JSP files. The JSP files call

    on EJBs and servlets to process requests.

  • 8/3/2019 iAS Dev Guide

    41/146

    Implementing Business Logic 4-1

    4Implementing Business Logic

    Recall that the Emp loyee Benefit sam ple ap plication follows the MVC d esign

    pat tern. This chapter discusses the m odel (M) and th e controller (C) in the

    application . The view (V) is covered in Chap ter 5, "Creating Presentation Pages".

    The business logic for the Emp loyee Benefit app lication consists of listing the

    emp loyee information, adding ben efits, and removing ben efits (see Section 2.1,

    "Requirements for the Samp le App lication") for a sp ecific employee.

    The database schema for the ap plication, wh ich you migh t find useful to review, is

    shown in Section 2.3, "Database Schema".

    s Section 4.1, "Objects Needed by th e Application"

    s Section 4.2, "Other Opt ions Considered But Not Taken"

    s Section 4.3, "Controller"

    s Section 4.4, "Action H and lers"

    s Section 4.5, "Emp loyee Data (Entity Bean)"

    s Section 4.6, "Benefit Data (Stateless Session Bean)"

    s Section 4.7, "Emp loyeeManager (Stateless Session Bean)"

    s Section 4.8, "Utility Classes"

    Objects Needed by the Application

  • 8/3/2019 iAS Dev Guide

    42/146

    4-2 Oracle9i Application Server Application Developers Guide

    4.1 Objects Needed by the Application

    JSP pages contain p resentation d ata an d they also invoke bu siness logic objects toperform certain operations (query emp loyee information, add benefits, and remove

    benefits). These objects can be p lain Java classes or EJB objects.

    The Employee Benefit app lication u ses EJBs because it might offer more functions to

    users in the futu re. The EJB container provid es services that the ap plication m ight

    need.

    What EJB objects d oes the app lication need?

    s An object to man age emp loyee data

    The application n eeds to query the database and display the retrieved d ata.

    This can be an entity bean.

    s An object to contain m aster benefit data

    The app lication uses this object to determ ine wh ich benefits a user does not

    have.

    s A session bean to manage the employee entity beans

    s A data access object (DAO)

    DAOs are u sed to connect to the d ata sou rce. The EJBs do n ot connect to the

    data source directly.

    s A Controller and ActionHand ler objects

    These objects are needed to implem ent the MVC design p attern for theapplication.

    s Utility objects

    The application u ses utility objects to per form sp ecific tasks . It has a class to

    print d ebugging m essages, and a class to define constants used by other classes

    in the app lication.

    Other Options Considered But Not Taken

  • 8/3/2019 iAS Dev Guide

    43/146

    Implementing Business Logic 4-3

    4.2 Other Options Considered But Not Taken

    The app lication could have u sed p lain Java classes to hold d ata and not u sed EJBs atall. But if the app lication grow s and contains more features, it might be easier to use

    EJBs because it comes w ith a container that p rovides services such as p ersistence

    and transactions.

    Another ad vantage of using EJB is that it is easier to find d evelopers wh o are

    familiar w ith the EJB stand ard. It takes longer for d evelopers to learn a

    "hom e-grown " prop rietary system.

    Here are some gu idelines to help you choose among EJBs, servlets, and normal Javaobjects.

    4.2.1 Conditions that Favor Using EJBsChoose EJBs when :

    s You n eed to mod el comp lex business logic.

    s You n eed to mod el comp lex relationships between bu siness objects.

    s You n eed to access your compon ent from different client typ es such as JSPs and

    servlets.

    s You need J2EE serv ices.

    4.2.2 Conditions that Favor Using Servlets

    Choose servlets wh en:

    s You n eed to ma intain state bu t d o not require J2EE services (HttpSession

    object).

    s You d o not need to d edicate servlet instances to individu al clients. In large

    dep loyments with thousands of concurren t users, maintaining one stateful

    session bean instance for each client m ay be a bottleneck. Servlets provide a

    lighter w eight alternative.

    s You n eed to temp orarily store state of business process within a single H TTP

    request and the request involves multiple beans.

    4.2.3 Conditions that Favor Using Normal Java ObjectsChoose norm al Java objects when:

    Other Options Considered But Not Taken

  • 8/3/2019 iAS Dev Guide

    44/146

    4-4 Oracle9i Application Server Application Developers Guide

    s You do not n eed built-in w eb and EJB services such as tran sactions, security,

    persistence, resource p ooling.

    s You n eed th e following features th at are not a llowed in EJBs:

    s accessing a local disk using thejava.io package

    s creating threads

    s using the synchronized keyword

    s using thejava.awt or javax.swing packages

    s listening to a socket or creating a socket server

    s mod ifying th e socket factory

    s using native libraries (JNI)

    s reading or w riting static variables

    Controller

  • 8/3/2019 iAS Dev Guide

    45/146

    Implementing Business Logic 4-5

    4.3 Controller

    The Controller servlet is the first object that hand les requests for the ap plication. Itcontains a mapp ing of actions to classes, and all it does is route requests to the

    correspon ding class.

    The init meth od in th e servlet defines the m app ings. In this case, the application

    hard codes the mapp ings in the file. It wou ld be more flexible if the m app ing

    information comes from a d atabase or a file.

    When th e Controller gets a request, it runs the doGet or the doPost meth od. Both

    meth ods call the process method, w hich looks up th e value of the action parameterand calls the corresponding class.

    package empbft.mvc;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    import java.util.HashMap;

    import empbft.util.*;

    /** MVC Controller servlet. Implements the controller

    in an Model View Control pattern.

    */

    public class Controller extends HttpServlet

    {

    /* Private static String here, not String creation out of the execution

    path and hence help to improve performance. */

    private static final String CONTENT_TYPE = "text/html";

    /** Hashtable of registered ActionHandler object. */

    private HashMap m_actionHandlers = new HashMap();

    /** ActionHandlerFactory, responsible for instantiating ActionHandlers. */

    private ActionHandlerFactory m_ahf = ActionHandlerFactory.getInstance();

    /** Servlet Initialization method.@param - ServletConfig

    @throws - ServletException

    */

    public void init(ServletConfig config) throws ServletException

    {

    super.init(config);

    Controller

  • 8/3/2019 iAS Dev Guide

    46/146

    4-6 Oracle9i Application Server Application Developers Guide

    //Register ActionHandlers in Hashtable, Action name, implementation String

    //This really ought to come from a configuration file or database etc....

    this.m_actionHandlers.put(SessionHelper.ACTION_QUERY_EMPLOYEE,"empbft.mvc.handler.QueryEmployee");

    this.m_actionHandlers.put(SessionHelper.ACTION_ADD_BENEFIT_TO_EMPLOYEE,

    "empbft.mvc.handler.AddBenefitToEmployee");

    this.m_actionHandlers.put(SessionHelper.ACTION_REMOVE_BENEFIT_FROM_EMPLOYEE,

    "empbft.mvc.handler.RemoveBenefitFromEmployee");

    }

    /** doGet. Handle an MVC request. This method expects a parameter "action"

    http://localhost/MVC/Controller?action=dosomething&aparam=data&anotherparam=moredata

    @param - HttpServletRequest request,

    @param - HttpServletResponse response,

    */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException

    {

    process(request, response);

    }

    /** doPost. Handle an MVC request. This method expects a parameter "action"

    http://localhost/MVC/Controller?action=dosomething&

    aparam=data&anotherparam=moredata

    @param - HttpServletRequest request,

    @param - HttpServletResponse response,

    */public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException

    {

    process(request, response);

    }

    private void process(HttpServletRequest request, HttpServletResponse response)

    {

    try

    {

    //Get the action from the request parameter

    String l_action = request.getParameter(SessionHelper.ACTION_PARAMETER);

    //Find the implemenation for this action

    if (l_action == null) l_action = SessionHelper.ACTION_QUERY_EMPLOYEE;

    String l_actionImpl = (String) this.m_actionHandlers.get(l_action);

    Controller

  • 8/3/2019 iAS Dev Guide

    47/146

    Implementing Business Logic 4-7

    if (l_actionImpl == null) {

    throw new Exception("Action not supported.");

    } ActionHandler l_handler = this.m_ahf.createActionHandler(l_actionImpl);

    l_handler.performAction(request,response);

    }

    catch(Exception e)

    {

    e.printStackTrace();

    }

    }

    }

    Action Handlers

  • 8/3/2019 iAS Dev Guide

    48/146

    4-8 Oracle9i Application Server Application Developers Guide

    4.4 Action Handlers

    The process meth od of the Controller servlet looks up the class that is mapp ed tothe request and calls createActionHandler in the ActionHandlerFactory class to

    instantiate an instance of the mapp ed class.

    The Emp loyee Benefit app lication m aps three actions to three classes. These classes

    mu st be subclasses of the AbstractActionHandlerabstract class, which implem ents

    th e ActionHandler interface, and mu st implement th e performAction method.

    Figure 41 shows the relationship between these classes.

    The performAction method checks whether the request came from a browser or awireless device, and forwards the request to the ap prop riate JSP file. For brow sers

    the JSP file returns H TML, while for wireless dev ices the JSP file returns XML. For

    example, the performAction method in QueryEmployee.java forward s requests

    from browsers to the queryEmployee.jsp file, but for requests from wireless devices

    the method forward s the requests to the queryEmployeeWireless.jsp file.

    Figure 41 Action handlers

    QueryEmployeeAddBenefitToEmployee RemoveBenefitFromEmployee

    AbstractActionHandler

    ActionHandler

    abstract class

    interface

    Employee Data (Entity Bean)

  • 8/3/2019 iAS Dev Guide

    49/146

    Implementing Business Logic 4-9

    4.5 Employee Data (Entity Bean)

    Employee data can be mapp ed to an Employee entity bean. The home and remoteinterfaces for the bean declare method s for retrieving employee data an d ad ding

    and removing benefits.

    Each instance of the bean represents data for one employee and the instances can be

    shared amon g clients. The EJB container instantiates entity bean s and wa its for

    requests to access the beans. By shar ing bean instan ces and instan tiating them

    before they are needed, the EJB container uses instances more efficiently and

    provid es better performance. This is imp ortant for app lications with a large num ber

    of clients.

    Entity beans are less u seful if the emp loyees table is very large. The reason is that

    you are using a lot of fine-grained objects in you r ap plication.

    Intern ally, the Employee bean stores emp loyee data in a member variable called

    m_emp of type EmployeeModel. This class has m ethod s for getting ind ividua l data

    items (such as email, job ID, ph one).

    Figure 42 Employee classes

    Employee Data (Entity Bean)

    Fig r 4 3 E l M d l l

  • 8/3/2019 iAS Dev Guide

    50/146

    4-10 Oracle9i Application Server Application Developers Guide

    Figure 43 EmployeeModel class

    4.5.1 Home InterfaceThe Employee entity bean has the following h ome interface:

    package empbft.component.employee.ejb;

    import java.rmi.RemoteException;

    import javax.ejb.*;

    public interface EmployeeHome extends EJBHome

    {

    public Employee findByPrimaryKey(int employeeID)

    throws RemoteException, FinderException;

    }

    The findByPrimaryKey meth od, which is required for all entity beans, enables

    clients to find an Employee object. It takes an emp loyee ID as its pr imary key.

    It is imp lemented in the EmployeeBean class as ejbFindByPrimaryKey. To find an

    Employee object, it uses a da ta access object (DAO) to connect to the database an d

    perform a query op eration based on the emp loyee ID.

    See Section 46, "Emp loyeeDAO classes" for details on DAOs.

  • 8/3/2019 iAS Dev Guide

    51/146

    Employee Data (Entity Bean)

    4 5 3 Persistence

  • 8/3/2019 iAS Dev Guide

    52/146

    4-12 Oracle9i Application Server Application Developers Guide

    4.5.3 PersistenceThe Employee entity bean u ses bean-managed persistence (BMP), rather th an

    container-man aged p ersistence. The bean controls when it up da tes data in the

    database.

    It uses BMP because th e emp loyees-to-benefits is a m any-to-many relationship , and

    an old version of Oracle9iAS (release 1022) does not support M:M relationship.

    4.5.4 Load Method

    The Employee entity bean imp lements the ejbLoad method, although the bean usesbean-managed p ersistence. The ejbLoad method queries the database (using the

    DAO) and up dates the data in the bean w ith the new d ata from the d atabase. This

    ensures that the beans data is synchronized w ith the data in the d atabase.

    ejbLoad is called after the user add s or removes benefits.

    // from EmployeeBean.java

    public void ejbLoad() {

    try {if (m_dao == null)

    m_dao = new EmployeeDAOImpl();

    Integer id = (Integer)m_ctx.getPrimaryKey();

    this.m_emp = m_dao.load(id.intValue());

    } catch (Exception e) {

    throw new EJBException("\nException in loading employee.\n"

    + e.getMessage());

    }

    }

    See also Section 4.5.6.3, "Load Method ", wh ich d escribes the load method in the

    DAO.

    4.5.5 EmployeeModel ClassThe imp lementation of the Employee bean u ses a variable of type EmployeeModel,

    wh ich contains all the employee details such as first nam e, last nam e, job ID, and soon. The following code snipp et from EmployeeBean shows m_emp as a class

    variable:

    public class EmployeeBean implements EntityBean

    {

    private EmployeeModel m_emp;

    ...

    Employee Data (Entity Bean)

    }

  • 8/3/2019 iAS Dev Guide

    53/146

    Implementing Business Logic 4-13

    }

    Code snipp et from EmployeeModel:public class EmployeeModel implements java.io.Serializable

    {

    protected int m_id;

    protected Collection m_benefits;

    private String m_firstName;

    private String m_lastName;

    private String m_email;

    private String m_phoneNumber;private Date m_hireDate;

    private String m_jobId;

    ...

    }

    Figure 45 Employee and EmployeeModel

    Employee entity bean

    EmployeeModel

    EmployeeModel m_emp

    int m_idCollection m_benefits

    String m_firstName

    String m_lastName

    String m_email

    String m_phoneNumber

    String m_hireDate

    String m_jobId

    Employee Data (Entity Bean)

    4.5.6 Data Access Object for Employee Bean

  • 8/3/2019 iAS Dev Guide

    54/146

    4-14 Oracle9i Application Server Application Developers Guide

    4.5.6 Data Access Object for Employee BeanData access objects (DAO) are the on ly classes in the app lication that comm un icate

    with the database, or in general, with a data source. The entity and session beans in

    the application do not commu nicate with the data source. See Figure 32.

    By d e-coup ling business logic from d ata access logic, you can change the da ta

    source easily and indep endently. For example, if the d atabase schema or the

    database vendor changes, you only have to u pd ate the DAO.

    DAOs have interfaces and imp lementations. EJBs access DAOs by invoking

    meth ods d eclared in the interface. The imp lementation contains code specific for a

    data source.

    For details on DAOs, see:

    http://java.sun.com/j2ee/blueprints/design_patterns/data_access_object/index.html

    4.5.6.1 Interface

    The EmployeeDAO interface declares the interface to the d ata sou rce. Entity andsession beans and other objects in th e app lication call these methods to perform

    operations on the data source.

    package empbft.component.employee.dao;

    import empbft.component.employee.helper.EmployeeModel;

    public interface EmployeeDAO {

    public EmployeeModel load(int id) throws Exception;

    public Integer findByPrimaryKey(int id) throws Exception;public void addBenefits(int empId, int benefits[]) throws Exception;

    public void removeBenefits(int empId, int benefits[]) throws Exception;

    }

    4.5.6.2 Implementation

    The implementation of the DAO is called EmployeeDAOImpl. It uses JDBC to

    connect to the database and execute SQL statements on the database. If the datasource changes, you need to up da te only the implemen tation, not the interface.

    Employee an d Benefit objects get an instance of the DAO and inv oke the DAOs

    methods. The following example show s how the addBenefits method in the

    Employee bean invokes a m ethod in the DAO.

    // from EmployeeBean.java

    Employee Data (Entity Bean)

    public void addBenefits(int benefits[])

  • 8/3/2019 iAS Dev Guide

    55/146

    Implementing Business Logic 4-15

    p

    {

    try {if (m_dao == null) m_dao = new EmployeeDAOImpl();

    m_dao.addBenefits(m_emp.getId(), benefits);

    ejbLoad();

    } catch (Exception e) {

    throw new EJBException ("\nData access exception in adding benefits.\n"

    + e.getMessage());

    }

    }

    The addBenefits method in the EmployeeDAOImpl class looks like the following:

    public void addBenefits(int empId, int benefits[]) throws Exception

    {

    String queryStr = null;

    PreparedStatement stmt = null;

    try {

    getDBConnection();

    for (int i = 0; i < benefits.length; i ++) {queryStr = "INSERT INTO EMPLOYEE_BENEFIT_ITEMS "

    + " (EMPLOYEE_ID, BENEFIT_ID, ELECTION_DATE) "

    + " VALUES (" + empId + ", " + benefits[i] + ", SYSDATE)";

    stmt = dbConnection.prepareStatement(queryStr);

    int resultCount = stmt.executeUpdate();

    if (resultCount != 1) {

    throw new Exception("Insert result count error:" + resultCount);

    }

    }

    } catch (SQLException se) {

    throw new Exception(

    "\nSQL Exception while inserting employee benefits.\n"

    + se.getMessage());

    } finally {

    closeStatement(stmt);

    closeConnection();

    }}

    The methods in EmployeeDAOImpl use JDBC to access the da tabase. Another

    imp lementation could use a d ifferent m echanism su ch as SQLJ to access the data

    source.

    Employee Data (Entity Bean)

    4.5.6.3 Load Method

  • 8/3/2019 iAS Dev Guide

    56/146

    4-16 Oracle9i Application Server Application Developers Guide

    After the Employee bean ad ds or removes benefits for an em ployee, it calls the load

    method in EmployeeDAOImpl:

    // from EmployeeBean.java

    public void addBenefits(int benefits[])

    {

    try {

    if (m_dao == null)

    m_dao = new EmployeeDAOImpl();

    m_dao.addBenefits(m_emp.getId(), benefits);

    ejbLoad();} catch (Exception e) {

    throw new EJBException ("\nData access exception in adding benefits.\n"

    + e.getMessage());

    }

    }

    // also from EmployeeBean.java

    public void ejbLoad()

    {

    try {

    if (m_dao == null)

    m_dao = new EmployeeDAOImpl();

    Integer id = (Integer) m_ctx.getPrimaryKey();

    this.m_emp = m_dao.load(id.intValue());

    } catch (Exception e) {throw new EJBException("\nException in loading employee.\n"

    + e.getMessage());

    }

    }

    The ejbLoad method in the Employee bean invokes load in the DAO object. By

    calling the load method after add ing or removing benefits, the app lication ensures

    that th e bean instance contains the sam e data as th e database for the specified

    employee.

    // from EmployeeDAOImpl.java

    public EmployeeModel load(int id) throws Exception

    {

    EmployeeModel details = selectEmployee(id);

    details.setBenefits(selectBenefitItem(id));

    return details;

    Employee Data (Entity Bean)

    }

  • 8/3/2019 iAS Dev Guide

    57/146

    Implementing Business Logic 4-17

    Note tha t the EJB container calls ejbLoad in the Employee bean au tomatically afterit runs the findByPrimaryKey meth od. See Section 6.2, "Query Emp loyee

    Operation" for d etails.

    Figure 46 EmployeeDAO classes

    Benefit Data (Stateless Session Bean)

    4.6 Benefit Data (Stateless Session Bean)

  • 8/3/2019 iAS Dev Guide

    58/146

    4-18 Oracle9i Application Server Application Developers Guide

    BenefitCatalog is a stateless session bean. It contains m aster benefit information

    such as benefit ID, benefit nam e, and benefit d escription for each benefit in th e

    benefits table in the d atabase.

    The app lication could h ave saved the benefit information to entity bean objects, but

    it uses a session bean instead . The reason for this is that th e master benefit

    information d oes not change within the application. It is more efficient for a session

    bean to retrieve the d ata only once w hen the EJB container creates the bean.

    Because the benefit information d oes not change, the BenefitCatalog bean does notneed a d ata access object (DAO) to p rovide d atabase access. The bean itself

    comm unicates w ith the database.

    Each instance of the session bean contains all the benefit information. You can create

    and pool multiple instances for imp roved concurrency and scalability. If the

    app lication used entity beans and you map ped a benefit to a bean, it would have

    required one instance per benefit.

    The bean is stateless so that one bean can be shared amon g many clients.

    Figure 47 BenefitCatalog classes

    4.6.1 Home InterfaceThe BenefitCatalog session bean has th e following home interface:

    Benefit Data (Stateless Session Bean)

    package empbft.component.benefit.ejb;

    import java rmi RemoteException;

  • 8/3/2019 iAS Dev Guide

    59/146

    Implementing Business Logic 4-19

    import java.rmi.RemoteException;

    import javax.ejb.EJBHome;import javax.ejb.CreateException;

    public interface BenefitCatalogHome extends EJBHome

    {

    public BenefitCatalog create() throws RemoteException, CreateException;

    }

    The create method, w hich is implemented in BenefitCatalogBean as ejbCreate,

    queries the benefits table in the d atabase to get a m aster list of benefits. Thereturn ed d ata (benefit ID, benefit nam e, benefit description) is saved to a

    BenefitModel object. Each record (that is, each ben efit) is saved to one

    BenefitModel object.

    The app lication gets a performan ce gain by retrieving the benefit d ata w hen th e EJB

    container creates the bean, instead of when it needs the data. The app lication can

    then query the bean when it needs the data.

    4.6.2 Remote InterfaceThe BenefitCatalog session bean has th e following rem ote interface:

    package empbft.component.benefit.ejb;

    import java.rmi.RemoteException;

    import javax.ejb.EJBObject;

    import java.util.Collection;

    public interface BenefitCatalog extends EJBObject

    {

    public Collection getBenefits() throws RemoteException;

    public void refresh() throws RemoteException;

    }

    The getBenefits method retu rns a Collection ofBenefitModels. This is the m aster

    list of all benefits. This method is called by the EmployeeManager bean (by the

    getUnelectedBenefitItems method) w hen the ap plication n eeds to display a u sers

    un elected ben efits. It comp ares a u sers elected benefits against the m aster list, and

    disp lays the benefits that are not elected. The u ser then selects benefits to add from

    this list.

    Benefit Data (Stateless Session Bean)

    4.6.3 Benefit Details

  • 8/3/2019 iAS Dev Guide

    60/146

    4-20 Oracle9i Application Server Application Developers Guide

    The BenefitCatalog bean contains a Collection ofBenefitModels. The BenefitModel

    class contains th e d etails (benefit ID, benefit nam e, and benefit d escription) for eachbenefit.

    The BenefitCatalog bean contains a class variable called m_benefits of type

    Collection. Data in the Collection are of type BenefitModel. Each BenefitModel

    contains information abou t a benefit (such as benefit ID, name, and description).

    BenefitItem is a su bclass ofBenefitModel.

    Figure 48 BenefitItem and BenefitModel classes

    JSPs call meth ods in BenefitModel to d isplay benefit information . For examp le,

    queryEmployee.jsp calls the getName method to display benefit name.

    None

    EmployeeManager (Stateless Session Bean)

    4.7 EmployeeManager (Stateless Session Bean)

  • 8/3/2019 iAS Dev Guide

    61/146

    Implementing Business Logic 4-21

    EmployeeManager is a stateless session bean that man ages access to the Employee entity bean. It is the only bean tha t JSPs can access directly; JSPs do not d irectly

    invoke the other beans (Employee an d BenefitCatalog ). To invoke methods on

    these beans, the JSPs go th rough EmployeeManager.

    Generally, a JSP shou ld not get an instance of an entity bean and invoke meth ods on

    the bean d irectly. It needs an interm ediate bean that manages session state with

    clients and im plemen ts business logic that deals with m ultiple beans. Without th is

    intermed iate bean, you need to w rite the business logic on JSPs, and JSPs shou ld

    have any bu siness logic at all. A JSPs sole responsibility is to presen t da ta.

    It is stateless because it d oes not contain data specific to a client.

    EmployeeManager contains method s (defined in the remote interface) that JSPs can

    invoke to execute bu siness logic operations. These methods invoke methods in the

    Employee an d BenefitCatalog beans.

    Examples:

    In addBenefitToEmployee.jsp:

    In removeBenefitFromEmployee.jsp:

  • 8/3/2019 iAS Dev Guide

    62/146

    4-22 Oracle9i Application Server Application Developers Guide

    Collection elected = mgr.getEmployeeDetails(empId).getBenefits();

    ...

    %>

    Figure 49 EmployeeManager classes

    4.7.1 Home InterfaceThe EmployeeManager has th e following h ome interface:

    package empbft.component.employee.ejb;

    import java.rmi.RemoteException;

    import javax.ejb.*;

    public interface EmployeeManagerHome extends EJBHome

    {

    public EmployeeManager create() throws RemoteException, CreateException;

    }

    The create method d oes nothing.

    EmployeeManager (Stateless Session Bean)

    4.7.2 Remote InterfaceTh EmployeeManager h th f ll i m t i t f

  • 8/3/2019 iAS Dev Guide

    63/146

    Implementing Business Logic 4-23

    The EmployeeManager has the following remote interface:

    package empbft.component.employee.ejb;

    import java.rmi.RemoteException;

    import javax.ejb.EJBObject;

    import java.util.Collection;

    import empbft.component.employee.helper.*;

    public interface EmployeeManager extends EJBObject

    {

    public Employee getEmployee(int id) throws RemoteException;

    public EmployeeModel getEmployeeDetails(int id) throws RemoteException;

    public Collection getUnelectedBenefitItems(int id) throws RemoteException;

    }

    getUnelectedBenefitItems in EmployeeManager invokes methods on th e

    BenefitCatalog bean an d retu rns a Collection to th e JSP, wh ich iterates throu gh an d

    disp lays the contents of the Collection.

    Methods in EmployeeManager also return non-bean objects to the app lication. For

    example, queryEmployee.jsp invokes the getEmployeeDetails method, w hich

    returns an EmployeeModel. The JSP can then invoke meth ods in EmployeeModel

    to extract the emp loyee da ta.

    // from queryEmployee.jsp

    ...

    Employee ID:

    First Name:

    Last Name:

    Similar ly, in removeBenefitFromEmployee.jsp, the p age calls getEmployeeDetails

    to get an EmployeeModel, then it calls the getBenefits method on the

    EmployeeModel to list the benefits for the em ployee. The u ser can then select

    which benefits shou ld be removed .

    // from removeBenefitFromEmployee.jsp

  • 8/3/2019 iAS Dev Guide

    64/146

    4-24 Oracle9i Application Server Application Developers Guide

    EmployeeManager mgr = SessionHelper.getEmployeeManager(request);

    Collection elected = mgr.getEmployeeDetails(empId).getBenefits();

    ...

    %>

    ...

    Select Elected Benefits


    Utility Classes

    4.8 Utility ClassesThe application u ses these u tility classes:

  • 8/3/2019 iAS Dev Guide

    65/146

    Implementing Business Logic 4-25

    The application u ses these u tility classes:

    s AppJNDINames defines constants u sed to locate beans and classes.

    s Debug contains methods th at write messages to the window wh ere you started

    OC4J.

    s SessionHelper defines constan ts used to identify names of parameters in the

    query string.

    Figure 410 Utility classes

    Utility Classes

  • 8/3/2019 iAS Dev Guide

    66/146

    4-26 Oracle9i Application Server Application Developers Guide

  • 8/3/2019 iAS Dev Guide

    67/146

    Creating Presentation Pages 5-1

    5Creating Presentation Pages

    You can create the p resentation pages, which can contain d ata from bu siness logic

    plus presentation elemen ts, using d ifferent methods:

    Contents of this chapter:

    s Section 5.1, "H TML Files"

    s Section 5.2, "Servlets"

    s Section 5.3, "JSPs"

    5.1 HTML FilesThis option is valid for static pages only. If your pages have d ynam ic da ta, you have

    to generate the p ages program matically.