[Sun Press] Your First Cup - An Introduction to the Java EE Platform

download [Sun Press] Your First Cup - An Introduction to the Java EE Platform

of 50

Transcript of [Sun Press] Your First Cup - An Introduction to the Java EE Platform

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    1/50

    Your First Cup:An Introduction tothe Java EE Platform

    Sun Microsystems, Inc.4150 Network CircleSanta Clara, CA95054U.S.A.

    PartNo: 8196451October 4, 2006

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    2/50

    Copyright2006 SunMicrosystems,Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Allrights reserved.

    Sun Microsystems, Inc. has intellectual propertyrights relating to technologyembodiedin the product that is describedin this document. In particular,and withoutlimitation, these intellectualproperty rightsmay include oneor more U.S. patents or pending patentapplications in theU.S. andin other countries.

    U.S. GovernmentRights Commercial software. Government usersare subject to the Sun Microsystems, Inc. standardlicense agreementand applicable provisionsof theFARand itssupplements.

    This distribution may include materialsdeveloped by third parties.

    Parts of theproductmay bederived from Berkeley BSDsystems,licensedfromthe University of California. UNIX is a registered trademarkin theU.S. andothercountries, exclusivelylicensedthrough X/Open Company, Ltd.

    Sun, SunMicrosystems,the Sunlogo,the Solaris logo, theJava CoffeeCup logo, docs.sun.com,Java,and Solaris are trademarks or registered trademarks of SunMicrosystems, Inc. in the U.S. and othercountries. All SPARC trademarksare used underlicense and aretrademarks or registered trademarks of SPARCInternational, Inc. in the U.S. and othercountries. Products bearing SPARC trademarksare basedupon an architecture developedby Sun Microsystems, Inc.

    TheOPEN LOOK andSunTM GraphicalUser Interfacewas developedby Sun Microsystems, Inc. for its users and licensees.Sun acknowledges the pioneeringeffortsof Xerox in researchingand developing theconcept of visualor graphicaluserinterfaces forthe computer industry. Sunholdsa non-exclusive license from XeroxtotheXerox GraphicalUserInterface, which license also coversSunslicensees whoimplement OPEN LOOK GUIs andotherwise complywithSunswritten licenseagreements.

    Productscoveredby andinformationcontained in this publication are controlled byU.S. ExportControl laws andmay be subject to theexport or importlaws inothercountries. Nuclear, missile, chemicalor biologicalweapons or nuclear maritime end uses or end users,whether direct or indirect, arestrictly prohibited. Exportorreexportto countriessubject to U.S. embargo or to entities identifiedon U.S. exportexclusion lists,including, butnot limited to,the deniedpersons andspeciallydesignatednationals listsis strictly prohibited.

    DOCUMENTATION IS PROVIDED AS ISAND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONSAND WARRANTIES, INCLUDINGANYIMPLIED WARRANTYOF MERCHANTABILITY, FITNESS FORA PARTICULARPURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED,EXCEPT TOTHEEXTENT THAT SUCH DISCLAIMERSARE HELD TOBE LEGALLY INVALID.

    Copyright2006 SunMicrosystems,Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Tousdroits rservs.

    Sun Microsystems, Inc. dtient les droits de proprit intellectuelle relatifs la technologie incorporedans le produit qui est dcrit dans ce document. En particulier,

    et cesans limitation, cesdroits de proprit intellectuellepeuvent inclure un ou plusieursbrevetsamricains ou desapplications de brevet en attente auxEtats-Unisetdansdautrespays.

    Cette distribution peutcomprendre des composants dvelopps par des tierces personnes.

    Certainescomposants de ce produit peuvent tredrivesdu logiciel Berkeley BSD, licencispar lUniversit de Californie. UNIX est une marque dpose auxEtats-Uniset dansdautrespays; elleest licencieexclusivementpar X/Open Company, Ltd.

    Sun, SunMicrosystems,le logo Sun, lelogo Solaris, le logo Java CoffeeCup, docs.sun.com,Java et Solaris sont desmarquesde fabrique ou desmarquesdposesdeSunMicrosystems,Inc. auxEtats-Uniset dans dautres pays. Toutes lesmarquesSPARCsont utilisessous licence et sont desmarquesde fabrique ou desmarquesdposes de SPARC International,Inc. aux Etats-Uniset dans dautres pays.Les produits portant les marques SPARC sont basssur une architecturedveloppe parSun Microsystems, Inc.

    Linterface dutilisation graphiqueOPEN LOOK et Suna tdveloppe parSun Microsystems, Inc. pour sesutilisateurs et licencis. Sunreconnat lesefforts de

    pionniersde Xerox pourla recherche et le dveloppementdu concept des interfaces dutilisation visuelle ou graphiquepour lindustrie de linformatique. Sun dtientune licence non exclusive de Xerox sur linterface dutilisation graphiqueXerox, cettelicencecouvrantgalementles licencisde Sun qui mettent en place linterfacedutilisation graphiqueOPEN LOOK etqui, en outre, se conforment auxlicences crites de Sun.

    Lesproduits quifontlobjet de cette publication et lesinformations quilcontientsont rgis parla legislation amricaine en matire de contrle desexportations etpeuvent tresoumis au droit dautres paysdans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pourdes armesnuclaires,des missiles, des armes chimiques ou biologiques ou pourle nuclairemaritime, directement ou indirectement, sont strictement interdites. Les exportations ourexportations vers des payssous embargo des Etats-Unis, ou vers des entits figurant sur les listes dexclusion dexportation amricaines, y compris, maisde manirenonexclusive,la liste de personnesqui font objet dun ordrede ne pasparticiper, dune faon directe ou indirecte, auxexportations desproduits ou desservicesquisont rgispar la legislation amricaineen matire de contrle des exportations et la listede ressortissants spcifiquement designs, sont rigoureusement interdites.

    LADOCUMENTATION EST FOURNIE "EN LETAT" ET TOUTES AUTRESCONDITIONS, DECLARATIONSET GARANTIES EXPRESSES OU TACITESSONTFORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEEPAR LA LOIAPPLICABLE,Y COMPRIS NOTAMMENT TOUTE GARANTIEIMPLICITE RELATIVEA LAQUALITE MARCHANDE,A LAPTITUDEA UNE UTILISATION PARTICULIERE OU A LABSENCE DE CONTREFACON.

    060914@15490

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    3/50

    Contents

    Preface .............................................................................................................................................................5

    1 Introduction .................................................................................................................................................... 9

    Goals of This Tutorial ..................................................................................................................................... 9

    Requirements for This Tutorial ..................................................................................................................... 9

    A Checklist ............................................................................................................................................... 9

    2 The Java Platform, Enterprise Edition ..................................................................................................... 11

    Differences between Java EE and Java SE ................................................................................................... 11

    The Java Programming Language Platforms ..................................................................................... 11

    Overview of Enterprise Applications .........................................................................................................12

    Tiered Applications ..............................................................................................................................12

    Java EE Servers ..............................................................................................................................................15

    Java EE Containers ...............................................................................................................................15

    3 CreatingYour First Java EEApplication ...................................................................................................17

    Architecture of the Example Application ..................................................................................................17

    Tiers in the Example Application ........................................................................................................18

    Java EE Technologies Used in the Example Application ..................................................................18

    Coding the Example Application ................................................................................................................18Getting Started ......................................................................................................................................18

    M Register the Server with NetBeans ..............................................................................................18

    M Create a Directory for the Example .............................................................................................19

    M Specify Some Settings ...................................................................................................................19

    Creating the Web Service Endpoint ....................................................................................................20

    Creating the Enterprise Bean ...............................................................................................................23

    Creating the Web Client .......................................................................................................................26Building, Packaging, Deploying, and Running the firstcup Enterprise Application ................42

    3

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    4/50

    M Preparing the Deployment Descriptor .......................................................................................43

    M Building and Packaging the firstcup Enterprise Application ...............................................43

    MDeploying the firstcup Enterprise Application ......................................................................43M Running the firstcup Application ............................................................................................44

    4 Building, Packaging, and Deploying and Running the Example Application ..................................45

    Building and Packaging the Example Application ...................................................................................45

    Building and Packaging the Example Application using ant ..........................................................45

    M Building and Packaging firstcup-dukes-age using ant .......................................................45MDeploying firstcup-dukes-age.war using ant ......................................................................46

    M Building and Packaging DukesBirthdayBean and firstcup using ant ................................46

    Deploying the Example Application ..........................................................................................................46

    Deploying the Enterprise Bean and Web Client ................................................................................46

    MDeploying firstcup.ear using ant ...........................................................................................46

    Running the Web Client ..............................................................................................................................47

    M Running the firstcup Application ....................................................................................................47

    Undeploying the Application ......................................................................................................................47

    MUndeploying with Ant ..........................................................................................................................47

    MUndeploying with Asadmin ................................................................................................................47

    5 Next Steps .....................................................................................................................................................49

    The Java EE Tutorial .....................................................................................................................................49

    More Information on the Java EE Platform ...............................................................................................49

    Java EE Servers ..............................................................................................................................................49

    The Sun Java SystemApplication Server ............................................................................................49

    Other Java EE Servers ...........................................................................................................................50

    Contents

    YourFirstCup: An Introductionto theJava EE Platform October 4, 20064

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    5/50

    Preface

    This isYourFirst Cup:An Introduction to JavaPlatform,Enterprise Edition, a short tutorial for

    beginning Java EE programmers. This tutorial is designed to give you a hands-on lesson ondeveloping an enterprise application from initial coding to deployment.

    Who Should Use This BookThis tutorial is for novice Java EE developers. You should be familiar with the Java programminglanguage, particularly the features introduced in Java Platform, Standard Edition 5. While familiarity

    with enterprise development and Java EE technologies is helpful, this tutorial assumes you are new todeveloping Java EE applications.

    Before You Read This BookBefore you start this tutorial, you should:

    I Be familiar with the Java programming languageI Be able to install software on your work machineI Have a modern web browser installed on your work machine

    Related Books and ProjectsThe following books and projects may be helpful to you in understanding this tutorial:

    I The Java EE5 TutorialI The Sun Java System Application Server documentation setI The NetBeans 5.5 documentation set

    5

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    6/50

    Related 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.

    Documentation, Support, and Training

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

    I Documentation (http://www.sun.com/documentation/)I Support (http://www.sun.com/support/)I Training (http://www.sun.com/training/)

    Typographic Conventions

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

    TABLE P1 Typographic Conventions

    Typeface Meaning Example

    AaBbCc123 The names of commands, files, and directories,

    and onscreen computer output

    Edit your .login file.

    Use ls -a to list all files.

    machine_name% you have mail.

    AaBbCc123 What you type, contrasted with onscreen

    computer outputmachine_name% su

    Password:

    aabbcc123 Placeholder:replacewith a realname orvalue The command toremove a file is rm

    filename.

    Preface

    YourFirstCup: An Introductionto theJava EE Platform October 4, 20066

    http://www.sun.com/documentation/http://www.sun.com/documentation/http://www.sun.com/documentation/http://www.sun.com/support/http://www.sun.com/support/http://www.sun.com/support/http://www.sun.com/training/http://www.sun.com/training/http://www.sun.com/training/http://www.sun.com/training/http://www.sun.com/support/http://www.sun.com/documentation/
  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    7/50

    TABLE P1 Typographic Conventions (Continued)

    Typeface Meaning Example

    AaBbCc123 Book titles, new terms, and terms to beemphasized

    Read Chapter 6 in the UsersGuide.

    A cache is a copy that is stored

    locally.

    Do notsave the file.

    Note: Some emphasized items

    appear bold online.

    Shell Prompts in Command ExamplesThe following table shows thedefault UNIX system prompt and superuser prompt for the C shell,Bourne shell, and Korn shell.

    TABLE P2 ShellPrompts

    Shell Prompt

    C shell machine_name%

    C shell for superuser machine_name#

    Bourne shell and Korn shell $

    Bourne shell and Korn shell for superuser #

    Preface

    7

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    8/50

    8

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    9/50

    Introduction

    An introduction to this tutorial. This chapter outlines the goals and the prerequisites for completingthis tutorial.

    Goals of This TutorialAt the completion of this tutorial, you will:

    I Understand the basics of tiered applicationsI Understand the basics of theJava EE platformI Have created a multi-tiered Java EE applicationI Have deployed and run your application on a Java EE serverI

    Know where to go next for more information on the Java EE platform

    Requirements for This Tutorial

    AChecklist

    To complete this tutorial, you need:

    I The tutorial bundleI The Java EE 5 Software Development KitI NetBeans 5.5 (optional)

    Getting the Tutorial Bundle

    To get the tutorial bundle, go to the projects java.net(https://firstcup.dev.java.net/servlets/ProjectDocumentList) site.

    1C H A P T E R 1

    9

    https://firstcup.dev.java.net/servlets/ProjectDocumentListhttps://firstcup.dev.java.net/servlets/ProjectDocumentListhttps://firstcup.dev.java.net/servlets/ProjectDocumentListhttps://firstcup.dev.java.net/servlets/ProjectDocumentListhttps://firstcup.dev.java.net/servlets/ProjectDocumentListhttps://firstcup.dev.java.net/servlets/ProjectDocumentList
  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    10/50

    GettingtheJavaEE5SDK

    TogettheJavaEE5SDK,goto http://java.sun.com/javaee/downloads/index.jsp.

    Getting NetBeans 5.5

    To get NetBeans 5.5 go to http://www.netbeans.org/downloads/index.html.

    Requirements for This Tutorial

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200610

    http://java.sun.com/javaee/downloads/index.jsphttp://java.sun.com/javaee/downloads/index.jsphttp://www.netbeans.org/downloads/index.htmlhttp://www.netbeans.org/downloads/index.htmlhttp://www.netbeans.org/downloads/index.htmlhttp://java.sun.com/javaee/downloads/index.jsp
  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    11/50

    The Java Platform, Enterprise Edition

    This chapter outlines thefeatures of Java EE, how it differs from Java SE and Java ME, and the basic

    concepts behind enterprise application development.

    Differences between Java EE and Java SEJava technology is both a programming language and a platform. The Java programming language is

    a high-level object-oriented language that has a particular syntax and style.A Java platform is a

    particular environment in which Java programming language applications run.

    There are several Java platforms. Many developers, even long-time Java programming language

    developers, do not understand how the different platforms relate to each other.

    The Java Programming Language Platforms

    There are three platforms of the Java programming language:

    I Java Platform, Standard Edition (Java SE)I Java Platform, Enterprise Edition (Java EE)I Java Platform, Micro Edition (Java ME)

    All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface

    (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that

    runs Java applications. AnAPI is a collection of software components that you can use to create other

    software components or applications. Each Java platform provides a virtual machine and an API, and

    this allows applications written for that platform to run on any compatible system with all the

    advantages of the Java programming language: platform-independence, power, stability,

    ease-of-development, and security.

    2C H A P T E R 2

    11

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    12/50

    Java SEWhen most people think of the Java programming language, they think of the Java SE API. Java SEs

    API provides the core functionality of the Java programming language. It defines everything fromthe basic types and objects of the Java programming language to high-level classes that are used fornetworking, security, database access, graphical user interface (GUI) development, and XMLparsing.

    In addition to the core API, the Java SE platform consists of a virtual machine, development tools,deployment technologies, and other class libraries and toolkits commonly used in Java applications.

    Java EEThe Java EE platform is built on top of the Java SE platform. Java EE provides an API and runtimeenvironment for developing and running large-scale, multi-tiered, scalable, reliable, and securenetwork applications.

    Java METhe Java ME platform provides an API and a small-footprint virtual machine for running Javaprogramming language applications on small devices, like cellular phones. TheAPI is a subset of the

    Java SE API, along with special class libraries useful for small device application development. JavaME applications are often clients of Java EE application services.

    Overview of Enterprise ApplicationsThis section describes enterprise applications and how they are designed and developed.

    As stated above, the Java EE platform is designed to help developers create large-scale, multi-tiered,

    scalable, reliable, and secure network applications. A shorthand name for such applications isenterprise applications, so called because these applications are designed to solve the problemsencountered by large enterprises. Enterprise applications are not only useful for large corporations,agencies, and governments, however. The benefits of an enterprise application are helpful, evenessential, for individual developers and small organizations in an increasingly networked world.

    The features that make enterprise applications powerful, like security and reliability, often makethese applications complex. The Java EE platform is designed to reduce the complexity of enterpriseapplication development by providing a development model,API, and runtime environment that

    allows developers to concentrate on functionality.

    TieredApplicationsIn a multi-tiered application, the functionality of the application is separated into isolated functionalareas, called tiers. Typically, multi-tiered applications have a client tier, a middle tier, and a data tier(often called the enterprise information systems tier). The client tier consists of a client program that

    makes requests to the middle tier. The middle tiers business functions handle client requests andprocess application data, storing it in a permanent datastore in the data tier.

    Overview of EnterpriseApplications

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200612

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    13/50

    Java EE application development concentrates on the middle tier to make enterprise applicationmanagement easier, more robust, and more secure.

    The Client Tier

    The client tier consists of application clients that access a Java EE server and that are usually locatedon a different machine from the server. The clients make requests to the server. The server processestherequests and returns a response back to theclient. Many different types of applications can beJava EE clients, and they are not always, or even often Java applications. Clients can be a web browser,a stand-alone application, or other servers, and they run on a different machine from the Java EEserver.

    The Web Tier

    The web tier consists of components that handle the interaction between clients and the business tier.Its primary tasks are the following:

    I Dynamically generate content in various formats for the client.

    I Collect input from users of the client interface and return appropriate results from the

    components in the business tier.I Control the flow of screens or pages on the client.

    I Maintain the state of data for a users session.

    I Perform some basic logic and hold some data temporarily in JavaBeans components.

    Java EE Technologies Used in the Web Tier

    The following Java EE technologies are used in the web tier in Java EE applications:

    TABLE21

    Technology Purpose

    Servlets Java programming language classes that dynamically

    process requests and construct responses, usually for

    HTMLpages

    JavaServer P ages ( JSP) Text-based d ocuments that are c ompiled i nto s ervlets

    and define how dynamic content can be added to

    static pages, such as HTML pages.

    JavaServer Faces technology A u ser-interface c omponent f ramework for web

    applications that allows you to include UI

    components (such as fields and buttons) on a page,

    convert and validate UI component data, save UI

    component data to server-side data stores, and

    maintain component state.

    Overview of EnterpriseApplications

    Chapter 2 The Java Platform, Enterprise Edition 13

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    14/50

    TABLE 21 (Continued)

    Technology Purpose

    JavaServerPages Standard TagLibrary Atag library thatencapsulatescore functionalitycommon to JSP pages

    JavaBeans Components Objects that act a s temporary d ata s tores f or the p ages

    of an application

    The Business Tier

    The business tier consists of components that provide the business logic for an application. Business

    logic is code that provides functionality to a particular business domain, like the financial industry, oran e-commerce site. In a properly designed enterprise application, the core functionality exists in thebusiness tier components.

    Java EE Technologies Used in the Business Tier

    The following Java EE technologies are used in the business tier in Java EE applications:

    I Enterprise JavaBeans (enterprise bean) componentsI JAX-WS web service endpointsI Java PersistenceAPI entities

    The Enterprise Information Systems Tier

    The enterprise information systems (EIS) tier consists of database servers, enterprise resourceplanning systems, and other legacy data sources, like mainframes. These resources typically arelocated on a separate machine than the Java EE server, and are accessed by components on the

    business tier.

    Java EE Technologies Used in the EIS Tier

    The following Java EE technologies are used to access the EIS tier in Java EE applications:

    I The Java Database Connectivity API (JDBC)I The Java Persistence APII The J2EE Connector ArchitectureI The Java Transaction API (JTA)

    Overview of EnterpriseApplications

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200614

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    15/50

    Java EE ServersA Java EE server is a server application that theimplements the Java EE platformAPIs and providesthe standard Java EE services. Java EE servers are sometimes called application servers, because theyallow you to serve application data to clients, much as how web servers serve web pages to webbrowsers.

    Java EE servers host several application component types that correspond to the tiers in amulti-tiered application. The Java EE server provides services to these components in the form of acontainer.

    Java EE ContainersJava EE containers are the interface between the component and the lower-level functionalityprovided by the Java EE platform to support that component. The functionality of the container isdefined by the Java EE platform, and is different for each component type. Nonetheless, the Java EEserver allows the different component types to work together to provide functionality in anenterprise application.

    The Web Container

    The web container is the interface between web components and the web server. A web componentcan be a servlet, a JSP page, or a JavaServer Faces page. The container manages the componentslifecycle, dispatches requests to application components, and provides interfaces to context data,such as information about the current request.

    TheApplication Client ContainerThe application client container is the interface between Java EE application clients, which arespecial Java applications that use Java EE server components, and the Java EE server. The applicationclient container runs on theclient machine, and is the gateway between the client application and theJava EE server components that the client uses.

    The EJB Container

    The EJB container is the interface between enterprise beans, which provide thebusiness logic in aJava EE application, and theJava EE server. The EJB container runs on theJava EE server andmanages the execution of an applications enterprise beans.

    JavaEE Servers

    Chapter 2 The Java Platform, Enterprise Edition 15

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    16/50

    16

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    17/50

    Creating Your First Java EEApplication

    This chapter gives an overview of the example application and step-by-step instructions on codingthe example application.

    Architecture of the Example ApplicationThe example application consists of three main components: DukesAgeService, a web serviceendpoint; DukesBirthdayBean, an enterprise bean; and firstcup, a web application created withJavaServer Faces technology.

    DukesAgeService is a JAX-WS endpoint that calculates theage of Duke, the Java mascot. Duke wasborn on May 23, 1995, when thefirst demo of Java technology was publicly released.

    DukesBirthdayBean is a stateless session bean that calculates the difference between the users ageand Dukes age.

    The firstcup web application is a JavaServer Faces application that accesses DukesAgeService todisplay Dukes age, reads in a date provided by the user, accessesDukesBirthdayBean to calculatewho is older, and then displays the difference in years between the user and Duke.

    The web application consists of the following:

    I greeting.jsp: AJSP page with which a user can enter a date

    I response.jsp: AJSP page that tells the user whether he or she is older or younger than Duke,based on thedate the user entered in the greeting.jsp page

    I DukesBDay.java: A JavaServer Faces managed bean that defines properties to hold the usersbirth date, get Dukes current age from the web service, and get the age difference between theuser and Duke from theenterprise bean.

    I faces-config.xml: A file used to configure resources for the JavaServer Faces application. In the

    case of this application, the file configures a resource bundle containing messages, the managedbean, DukesBDay, and the page navigation rules.

    3C H A P T E R 3

    17

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    18/50

    I web.xml: The web applications deployment descriptor, which is used to configure certain aspectsof a web application when it is installed. In this case, it is used to provide a mapping to theapplications FacesServlet instance, which accepts incoming requests, passes them to the life

    cycle for processing, and initializes resources.

    Tiers in the Example ApplicationThe example application has one web tier component (the firstcupweb client) and two business tiercomponents (the DukesAgeServiceweb service and the DukesBirthdayBeanenterprise bean). Theusers web browser is the client tier component, as it accesses the rest of theapplication through the

    web tier. The example application does not access the EIS tier.

    Java EE Technologies Used in the Example ApplicationThe DukesAgeService web service endpoint is a JAX-WS endpoint The DukesBirthdayBeanenterprise bean is a stateless session bean. The firstcupweb client is a JavaServer Faces applicationthat runs in the web container of the Java EE server.

    Coding the Example ApplicationThis section describes how to code the example application.

    Getting StartedBefore you start coding the example, you need to perform some set-up tasks:

    1. Register the server with your NetBeans IDE.2. Create a directory for theexample you will build.3. Specify some settings.

    M Register the Server with NetBeans

    Launch the NetBeans IDE.

    From the menu, select ToolsServer Manager.

    Click Add Server.

    In the Add Server Instance dialog, select SunJava System Application Server from the Server menu.

    (Optional) Enter a namefor the server in the Namefield.

    1

    2

    3

    4

    5

    Codingthe Example Application

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200618

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    19/50

    Click Next.

    Click Browse to find thelocation of theApplication Server installation.

    Click Next.

    Enter theuser name youchose when you installed the Application Serverin the Admin Username

    field.

    Enter thepassword for this username in theAdmin Password field.

    Click Finish.

    Click Close.

    M Create a Directory for the Example

    Createanother directory at thesame level as the example directory andcall it myexample. Youll put

    the First Cupapplication that you build while following this tutorial in this directory.

    Copy theentirebp-project folder from the example directory to the myexample directory.

    M Specify Some Settings

    Inthe myexample/bp-project directory, copy the build.properties.sample fileto

    build.properties.

    Open the build.properties file ina text editor.

    Set the javaee.home property to the path of your Application Serverinstallation. Use forward

    slashes in the path, even if you are onthe Windows platform. For example, you would enter

    C:/myServer instead ofC:\myServer.

    Set the firstcup.tutorial.home property to thelocation of your firstcup tutorial installation,suchas C:/firstcup.

    Change example to myexample inthepathspecifiedbythejavaee.server.passwordfile property.

    Open the admin-password.txt file from the myexample/bp-project directory in a text editor.

    Set the AS_ADMIN_PASSWORD property to your Application Server password.

    Save the build.properties and admin-password.txt files andclose them.

    6

    7

    8

    9

    10

    11

    12

    1

    2

    1

    2

    3

    4

    5

    6

    7

    8

    Codingthe Example Application

    Chapter 3 Creating Your First Java EE Application 19

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    20/50

    Creating the Web Service Endpoint

    The DukesAgeService endpoint is a simple web service. Web services are web-based applications

    that use open, XML-based standards and transport protocols to exchange data with calling clients.Both the requests and responses are sent as XML documents, and are usually sent as HTTP packets.This makes interoperability between different systems and applications easy, as it is not necessary forthe client to know the underlying architecture of the server and vice-versa to make a successful webservice call.

    Web services are designed to be independent of the client. Typically web service endpoints arepublicly available to a wide variety of clients, and the clients are located throughout the internet. This

    is called loose coupling, as the clients and servers are connected only by the standard XML-basedrequests and responses. For this reason, DukesAgeService will be developed in its own applicationmodule, and deployed separately from the DukesBirthdayBean enterprise bean and firstcup webclient.

    JAX-WS Endpoints

    DukesAgeService is a JAX-WS endpoint implemented as a servlet. Servlets are web components thatrun in the web container.

    Well begin by creating a servlet class, then decorate theclass with the @WebServiceannotation tomake the class a web service endpoint, and finally we will add the getDukesAge method to calculateand return Dukes age.

    Creating the Endpoint

    In NetBeans or another editor, create a Java class source file called DukesAge.java in thecom.sun.firstcup.webservice package.

    M Create the Project in NetBeans

    SelectFileNew Project.

    Select Web in the Categories pane.

    Select Web Application in the Projects pane.

    Click Next.

    Set Project Name to firstcup-dukes-age.

    Set theProject Location to /myexample, inwhich INSTALL is the location ofthe firstcup

    tutorial installation.

    Select your Application Server from theServermenu.

    1

    2

    3

    4

    5

    6

    7

    Codingthe Example Application

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200620

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    21/50

    Select JavaEE 5 from the JavaEE Version menu.

    Set Context Path to /DukesAgeService

    Click Finish.

    You should now see the module you created in the Projects pane.

    From theProjects pane, right-click on theindex.jsp file andselect Delete. Click Yes in the dialog.

    M Create the DukesAge Class

    SelectFileNewFile.

    Make sure firstcup-dukes-age is selected in theProject menu.

    Select Java Classesin the Categories pane.

    Select Java Class in the File Types pane.

    Click Next.

    Set Class Nameto DukesAge.

    Set Package to com.sun.firstcup.webservice.

    Click Finish.

    You should now see the DukesAge.java file inside the com.sun.firstcup.webservice package inthe Projects pane. The DukesAge.java file should also be open in the editor pane.

    M Annotate the DukesAge Class as a Web Service

    Adda @WebService annotation to the class.

    @WebService

    public class DukesAge {

    ...

    }

    M Remove the Default Constructor

    Highlight thefollowingdefault constructor anddeleteit, as web service endpoints do notrequire a

    default constructor.

    public DukesAge() {

    }

    8

    9

    10

    11

    1

    2

    3

    4

    5

    6

    7

    8

    Codingthe Example Application

    Chapter 3 Creating Your First Java EE Application 21

    C di h E l A li i

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    22/50

    M Add the getDukesAge Method

    Createa public getDukesAge method with a return type ofint.

    public int getDukesAge() {

    }

    Adda @WebMethod annotationto getDukesAge.

    @WebMethod

    public int getDukesAge() {

    }

    Add the following code to getDukesAge:

    Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);

    Calendar now = Calendar.getInstance();

    int dukesAge = now.get(Calendar.YEAR) - dukesBirthday.get(Calendar.YEAR);

    dukesBirthday.add(Calendar.YEAR, dukesAge);

    if (now.before(dukesBirthday)) {dukesAge--;

    }

    return dukesAge;

    M Resolve the Import Statements

    Right-click in the Editor.

    Select Fix Imports.

    In the Fix Imports dialog, choose the javax.jws.WebService package for the WebService class.

    SelectFileSavefromthe menu to savethe file.

    Building and Deploying the Web Service

    M Building DukesAgeService

    Select firstcup-dukes-age in theProjects tab.

    Right-clickfirstcup-dukes-age and select Build Project.

    1

    2

    3

    1

    2

    3

    4

    1

    2

    Codingthe Example Application

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200622

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    23/50

    M Deploying the Web Service EndpointThe DukesAgeService endpoint was packaged in a WAR file, firstcup-dukes-age.war. Now youll

    deployfirstcup-dukes-age.war

    to theApplication Server. This task gives instructions ondeploying firstcup-dukes-age.war in NetBeans.

    Select firstcup-dukes-age in the Projects tab.

    Right-clickfirstcup-dukes-age and select Deploy Project.

    Creating the Enterprise BeanDukesBirthdayBean is a stateless session bean. Stateless session beans are beans that do not maintaina conversational state with a client. With stateless session beans the client makes isolated requeststhat do not depend on any previous state or requests. If you require conversational state, you usestateful session beans.

    To create DukesBirthdayBean you need to create two Java source files: DukesBirthdayBean,theenterprise bean class; and DukesBirthdayRemote, the enterprise bean business interface. The

    enterprise bean class and the business interface are the only files you need to create an enterprisebean.

    Creating DukesBirthdayBean in NetBeans

    This section has instructions for creating the enterprise application and DukesBirthdayBeanenterprise bean.

    M Creating the EnterpriseApplicationIn this task, you will create an enterprise application archive (EAR) that will contain theDukesBirthdayBean enterprise bean and firstup web client.

    SelectFileNew Project.

    Select Enterprise in the Categories pane.

    Select Enterprise Application in the Projects pane.

    Click Next.

    Set Project Name to firstcup.

    Set the Project Location to /myexample.

    By default the wizard creates an enterprisebean modulefirstcup-ejb anda webapplication

    module firstcup-war. Leave everythingin the dialog asit is.

    1

    2

    1

    2

    3

    4

    5

    6

    7

    Codingthe Example Application

    Chapter 3 Creating Your First Java EE Application 23

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    24/50

    Click Finish.

    M Setting the Context RootIn this task, you will specify thecontext root to identify the web application in a J2EE server.

    Expand the firstcup module in the Projects pane.

    In the Configuration Files node, double-click the application.xml file.

    In application.xml, locate the context-root element.

    Changethe context root from /firstcup-war to /firstcup.

    SelectFileSavetosavethefile.

    Rightclick the firstcup-war modulein the Projects pane.

    Select Properties from thepopup menu.

    In the Categories tree, select Run.

    Changethe Context Path to /firstcup.

    Click OK.

    M Creating the DukesBirthdayBeanEnterprise Bean Class

    Now youll create the enterprise bean class and business interface source files in NetBeans. TheDukesBirthdayRemote business interface is a remote interface.

    Select firstcup-ejb project in the Projects tab.

    SelectFileNewFile.

    Select Enterprisein theCategories pane.

    Select Session Bean in the File Types pane.

    Click Next.

    SetEJBNameto DukesBirthdayBean.

    Set the Package nameto com.sun.firstcup.ejb.

    Set the SessionType to Stateless.

    8

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    1

    2

    3

    4

    5

    6

    7

    8

    Codingthe Example Application

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200624

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    25/50

    Uncheck Local and check Remote under CreateInterface.

    Click Finish.

    M Modify DukesBirthdayBean.javaNow youll add the code that calculates the difference in age in years between Duke and the user.

    In DukesBirthdayBean.java, delete the empty default constructor that NetBeans generated.

    Directly after the class declaration, paste in the following code:

    private static Logger logger =

    Logger.getLogger("com.sun.firstcup.ejb.DukesBirthdayBean");

    public int getAgeDifference(Date date) {

    int ageDifference;

    Calendar theirBirthday = new GregorianCalendar();

    Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);

    // Set the Calendar object to the passed in DatetheirBirthday.setTime(date);

    // Subtract the users age from Dukes age

    ageDifference = dukesBirthday.get(Calendar.YEAR) -

    theirBirthday.get(Calendar.YEAR);

    logger.info("Raw ageDifference is: " + ageDifference);

    // Check to see if Dukes birthday occurs before the users. If so,

    // subtract one from the age difference

    if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {ageDifference--;

    }

    logger.info("Final ageDifference is: " + ageDifference);

    return ageDifference;

    }

    Right-click in theeditorwindowand select Fix Imports.

    Choose the java.util.logging.Logger fully-qualified namefor the Logger class.

    Choose the java.util.Date fully-qualified namefor the Date class.

    Click OK.

    Right-click within the new getAgeDifference method andselect EJB MethodsAdd to Remote

    Interface.

    9

    10

    1

    2

    3

    4

    5

    6

    7

    Codingthe Example Application

    Chapter 3 Creating Your First Java EE Application 25

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    26/50

    SelectFileSave.

    M

    Modify DukesBirthdayRemote.javaExpand the firstcup-ejb module in theProjects pane.

    Double-clickDukesBirthdayRemote.java underSourcePackagescom.sun.firstcup.ejb.

    Right-click in the editor window andselect Fix Imports.

    Select java.util.Date as thefully-qualified class name of theDate class and click OK.

    Remove the throws clause from the method definitionso that you areleft with int

    getAgeDifference(Date date);.

    SelectFileSave.

    Creating the Web ClientTo create theweb client, you need to perform the following tasks:

    I Set the firstcup-war module to support JavaServer Faces technology. This will create a web.xmlfile that has a mapping to FacesServlet.

    I Create a web service client.

    I Create a resource bundle to hold localized messages used by the JSP pages.

    I

    Configure the resource bundle in the configuration file.I Create the DukesBDay managed bean class.

    I Configure DukesBDay in the configuration file.

    I Create the greeting.jsp page.

    I Configure the navigation rules in the configuration file.

    I Create the response.jsp page.

    Setting firstcup-war to support JavaServer Faces Technology

    All JavaServer Faces applications must include a mapping to the FacesServlet instance in theirdeployment descriptors. The FacesServlet instance accepts incoming requests, passes them to thelife cycle for processing, and initializes resources.

    You create the mapping to FacesServlet in the web applications deployment descriptor. Ratherthan adding the mapping to the web.xml file directly, NetBeans will create the web.xml fileandperform the mapping to FacesServlet for you when you specify that your web application supportsJavaServer Faces technology. To do this, perform the following task.

    8

    1

    2

    3

    4

    5

    6

    g p pp

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200626

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    27/50

    M Setting firstcup-war to support JavaServer Faces technology

    Right-click the firstcup-war moduleof the firstcup enterprise application in theProjects pane.

    Select Properties from the popup menu.

    Select Frameworks from the Categories tree.

    Click Add.

    Select JavaServer Faces from the listof choices in the dialog.

    Click OK.

    Change theservlet URLmapping to /firstcupWeb/*.

    This path will be the path to the FacesServlet instance.All requests must include this path in

    between the applications context path and the page in the URL. Users dont have to include this path

    in the URL because firstcup includes an index.jsp page that forwards users to the greeting.jsp

    page when they enter the following URL:http://localhost:8080/firstcup

    De-select the Validate XML checkbox.

    Click OK.

    The remaining steps tell you how to perform the forward to greeting.jsp from the index.jsp page.

    Expand thefirstcup-war modulein the Projects pane anddouble-click Web Pages.

    Right-clickwelcomeJSF.jsp, select Delete fromthe popup menu, and click Yes in the dialog.

    Double-clickindex.jsp.

    NetBeans generated this file when you created the firstcup project.

    Delete everythingon the page.

    Enter thefollowingin the index.jsp page:

    Save the file by selecting FileSave from the menu bar.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    Chapter 3 Creating Your First Java EE Application 27

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    28/50

    Creating a Web Service Client for the firstcup-war Web Module

    The firstcup-war web module must consume the firstcup-dukes-age web service in order to getDukes current age. For this to happen, you need to create a web serviceclient for the firstcup-warweb module.

    M Creating a Web Service Client for the firstcup-war Web Module

    Select firstcup-war from the Project pane.

    SelectFileNewFile.

    Select Web Services from the Categories pane.

    Select Web Service client from the File Typespane.

    Click Next.

    Select WSDL URL.

    Into the WSDLURL field,enter the following location ofthe WSDLfile ofthe web service that the web

    serviceclient will consume.

    http://localhost:8080/DukesAgeService/DukesAgeService?WSDL

    Into the Package field, enter the following package where the client files will be generated.

    com.sun.firstcup.webservice

    Click Finish.

    Creating a Resource Bundle

    In this section, well create theresource bundle that contains the static text and error messages usedby the JSP pages. The firstcup client supports both English and Spanish locales. Therefore we needto create two properties files, each of which will contain themessages for one of the locales.

    M Creating a Resource Bundle

    Right-clickfirstcup-war in the Projects pane.

    Select NewProperties File from thepopup menu.

    In the NewProperties File dialog, enter WebMessages in the File Name field.

    In the Folder field, enter src/java/com/sun/firstcup/web as the location of the file.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    1

    2

    3

    4

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200628

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    29/50

    Click Finish.

    After NetBeans creates theproperties file, enter the followingmessages or copy them from here to

    the file:Welcome=Hi. My name is Duke. Let us find out who is older -- You or me.

    DukeIs=Duke is

    YearsOldToday=years old today.

    Instructions=Enter your birthday and click submit.

    YourBD=Your birthday

    Pattern=MM/dd/yyyy

    DateError=Please enter the date in the form MM/dd/yyyy.

    YouAre=You are

    Year=year

    Years=years

    Older=older than Duke!

    Younger=younger than Duke!

    SameAge= the same age as Duke!

    Submit=Submit

    Back=Back

    These messages will be referenced from the JSP pages.

    Save the file by selecting FileSave from the menu.

    To add the Spanishtranslations of the messages, copy the properties file

    WebMessages_es.properties from

    /firstcup/example/firstcup/firstcup-war/src/java/com/sun/firstcup/webto

    /firstcup/myexample/firstcup/firstcup-war/src/java/com/sun/firstcup/web.

    You can create multiple properties files, each with a set of messages for a different locale. By storing

    localized static text and messages in resource bundles, you dont need to create a separate set of JSPpages for each locale.

    Refresh the files in theapplication by selecting FileRefreshAll Files from the menu bar.

    Configuring the Resource Bundle in the Configuration File

    To make the resource bundle available to the application, you need to configure it in the

    configuration file, by performing the following task.

    M Configuring the Resource Bundle

    Expand thefirstcup-war modulein the Projects pane.

    Open the folders Web PagesWEB-INF.

    Double-clickfaces-config.xml.

    5

    6

    7

    8

    9

    1

    2

    3

    Chapter 3 Creating Your First Java EE Application 29

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    30/50

    Before the end-tag of the faces-config element, add the following elements:

    com.sun.firstcup.web.WebMessages

    bundle

    en

    es

    The base-name element of the resource-bundle element identifies the fully-qualified class name of

    the resource bundle. The var element identifies thename by which the JSPpages will reference the

    resource bundle. The locale-config element identifies the locales supported by the resource

    bundle.

    Save the fileby selecting FileSave from the menu bar.

    Adding a Dependency on the Enterprise Bean Module

    The firstcup-war module depends on some classes in the firstcup-ejb module. You need to tell

    NetBeans that this dependency exists by performing the following task.

    M Adding a Dependency on the Enterprise Bean Module

    Right-click the firstcup-war module in the Projects pane.

    SelectProperties.

    Select Libraries from the Categories pane.

    Select Add Project.

    Navigate to /myexample/firstcup.

    Select the firstcup-ejb project.

    Click Add Project JAR Files.

    Make sure Build Required Projects is selected.

    Click OK.

    4

    5

    1

    2

    3

    4

    5

    6

    7

    8

    9

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200630

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    31/50

    Creating the DukesBDay Managed Bean Class

    The DukesBDay JavaBeans component is a backing bean. A backing bean is a JavaServer Facesmanaged bean that acts as a temporary data storage for the values of the components included on aparticular JavaServer Faces page. A managed bean is a JavaBeans component that a JavaServer Facesapplication instantiates and stores in scope. The section following this one describes more aboutmanaged beans and how to configure them.

    This section describes how to create the DukesBDay class. To create the class you need to do thefollowing:

    I Create an empty class.

    I

    Decorate the bean with a web service reference and an enterprise bean reference.I Add a property that accesses Dukes current age from the web service.

    I Add a property that accesses the users current birth date.

    I Add a property that accesses the age difference from the DukesBirthdayBean enterprise bean.

    I Add a property that acceses the absolute value of the age difference.

    M

    Creating an empty class.Right-click the firstcup-war modulein the Projects pane.

    Select New Java Class

    Enter DukesBDay in the Class Name field.

    Enter com.sun.firstcup.web in the Package field.

    Click Finish.

    M Adding an Enterprise Bean Reference

    Directly after the class declaration, add a privatevariable to hold a reference to the enterprise bean

    using the @EJB annotation:

    @EJB

    private DukesBirthdayRemote dukesBirthday;

    M Adding Properties to the BeanDuring this task, you will add the following properties to the DukesBDay bean:

    I age for getting Dukes age from the web service.I yourBD to hold the users birth date.I ageDiff to get the age difference from the enterprise bean.

    1

    2

    3

    4

    5

    Chapter 3 Creating Your First Java EE Application 31

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    32/50

    I absAgeDiff to hold theabsolute value of the age difference.

    After the dukesBirthday variable declaration, add the following private variables:

    private int age;

    private Date yourBD;

    private int ageDiff;

    private int absAgeDiff;

    Initialize the variables by adding thefollowinginside thedefault constructor:

    age = -1;

    yourBD = null;

    ageDiff = -1;

    absAgeDiff = -1;

    M Generating theAccessor Methods for the Properties

    Right-click in the editorwindow.

    SelectRefactorEncapsulate Fields from the popup window.

    In the Encapsulate Fields dialog, de-select the getDukesBirthday checkbox andthe

    setDukesBirthday checkbox.

    Click Next.

    Click Do Refactoring in the Refactoring pane at the bottom of theIDE window.

    You should now see two methods for each property, one to set the value and oneto get the value of

    the variable for that property.

    M Getting Dukes CurrentAge

    While performing this task, you will add some code to the getAge method to access Dukes current

    age from the web service.

    Expand the firstcup-war module.

    Expand the Web Service References node in thefirstcup-war module.

    From within theWebService References node, go to

    DukesAgeServiceDukesAgeServiceDukesAgePortgetDukesAge.

    1

    2

    1

    2

    3

    4

    5

    1

    2

    3

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200632

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    33/50

    Drag the getDukesAge operationfrom inside the DukesAgePort nodetothe getAge method in

    DukesBDay.java in the editor, directly before the return age; statement so that your getAge

    method looks likethis:

    public int getAge() {

    try { // Call Web Service Operation

    com.sun.firstcup.webservice.DukesAgeService service =

    new com.sun.firstcup.webservice.DukesAgeService();

    com.sun.firstcup.webservice.DukesAge port =

    service.getDukesAgePort();

    // TODO process result here

    int result = port.getDukesAge();System.out.println("Result = "+result);

    } catch (Exception ex) {

    // TODO handle custom exceptions here

    }

    return age;

    }

    In the getAge method ofDukesBDay, change the line int result = port.getDukesAge(); so thatthe age variable rather than the result variable is set to the result ofthe call to port.getDukesAge:

    age = port.getDukesAge();

    Remove the following line from the getAge method.

    System.out.println(Result = +result);

    M Getting the Age Difference From the DukesBirthdayBean EnterpriseBean

    During this task, you will add code to the getAgeDiff method to get the difference in age between

    the users age and Dukesage from the EJB and to set the absAgeDiff variable to the absolute value of

    the age difference.

    Inside the getAgeDiff method, directly beforethe return statement, add the following code:

    ageDiff = dukesBirthday.getAgeDifference(yourBD);

    if(ageDiff < 0){

    setAbsAgeDiff(Math.abs(ageDiff));

    } else {

    setAbsAgeDiff(ageDiff);

    }

    4

    5

    6

    Chapter 3 Creating Your First Java EE Application 33

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    34/50

    M Adding Import Statements

    Right-click in the editorwindow.

    Select Fix Imports from the popup menu.

    Select java.util.Date as the fully qualified name ofthe Date class.

    Click OK.

    M

    Saving DukesBDaySelectFileSave.

    Configuring the DukesBDay Bean in the Configuration File

    JavaServer Faces technology allows you to use the configuration file to initialize, configure, and storemanaged beans in one of the following scopes:

    I

    request, which begins when the user submits a page and ends when the response is rendered.I session, which begins when a user first accesses a page and ends when the users session ends,

    such as when the users session times out.

    I application, which lasts until the server stops the application.

    Once a bean is configured, a JavaServer Faces page can create and access the bean. In this section,well configure the DukesBDay managed bean.

    M Configuring the DukesBDay Managed Bean

    Expand the firstcup-war module in theProjects pane.

    Open the folders Web PagesWEB-INF.

    Double-clickfaces-config.xml.

    Right-click in the editor window andselect JavaServer FacesAdd Managed Bean.

    In the Add Managed Bean dialog, enter dukesBDay in the Bean Namefield.

    Enter com.sun.firstcup.web.DukesBDay in the BeanClass field.

    Select session from the scope menu.

    Enter DukesBDay backing bean in the Bean Description field.

    1

    2

    3

    4

    1

    2

    3

    4

    5

    6

    7

    8

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200634

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    35/50

    Click Add.

    You should now see the following in the faces-config.xml file:

    DukesBDay backing bean

    dukesBDay

    com.sun.firstcup.web.DukesBDay

    session

    The managed-bean-name element is the name by which the JavaServer Faces pages will refer to thebean. The managed-bean-class element is the fully-qualified class name of the bean. Themanaged-bean-scope element is thescope in which the bean is saved. We specify session scope

    because we need an instance of the bean to be available for the entire session so that all pages canaccess the values held by thebean.

    SelectFileSavetosavethefile.

    Creating the greeting.jsp Page

    The greeting.jsp page includes the welcome message, displays Dukes current age, and accepts theusers birth date. To create the page, you need to perform the following tasks:

    I Create an empty JSP page.

    I Declare the JavaServer Faces tag libraries.

    I Add an f:view and an h:form tag.

    I Add the output label components to display localized messages and text.

    I Add an input component to accept the birth date.

    I Register a converter on the input component to convert the date to the proper type.

    I Add a custom error message to display if conversion fails.

    I Add a button component so that the user can submit thepage.

    Creating an Empty JSP Page

    To create an empty JSP page, do the following:

    1. Rightclick on the firstcup-war module in the Projects pane.

    2. Select New JSPfromthe popup menu.

    3. Enter greeting in the JSP File Name field.

    4. Click Finish.

    5. In the greeting.jsp file, after the html tag, replace anyhead tag that is already in the page andadd the following one, which defines the content type:

    9

    10

    Chapter 3 Creating Your First Java EE Application 35

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    36/50

    Firstcup Greeting Page

    6. Remove the beginning and ending body tags.

    7. Remove JSP Page from the file.

    8. Select File Save to save the file.

    Declaring the JavaServer Faces Tag Libraries

    JavaServer Faces technology defines JSP custom tags for representing UI components, converters,validators, and event listeners on a JSP page. A custom tag provides a way to reference some Java logicfrom a JSPpage, thereby freeing page authors from including the logic in the page and allowing themto reuse the logic by adding the same tag in any of their JSP pages. See the Custom Tags chapter of theJava EE tutorial (http://java.sun.com/javaee/5/docs/tutorial/doc) for more information.

    Custom tags are defined in tag libraries. JavaServer Faces technology defines two tag libraries. TheHTML Render Kit library defines all of the standard UI component tags. Each instance of acomponent tag used on a page represents a corresponding stateful component object on the server.The core tag library defines tags for representing type converters, data validators, event listeners, andother objects and functions. Similarly to the component tags, each instance of a converter, validator

    or listener tag represents an object on the server.

    To use the tags in a page, you need to declare the tag libraries.

    To declare the tag libraries, do the following:

    1. After theending head tag in greeting.jsp,adda taglib declaration for the HTMLrender kittag library:

    When using a particular tag from this tag library, a page author must use the prefix h: to specifyin which tag library the tag is defined. The uri resolves to the tag library definition.

    2. After the taglib declaration from the previous step, add a taglib declaration for the core taglibrary:

    Again, when the page author uses a tag from this library, he or she must use the f: prefix tospecify that the tag is defined in the core tag library.

    Adding the f:view and f:form Tags

    A JavaServer Faces page is represented by a tree of UI components. When a JavaServer Facesimplementation processes the page during the pages life cycle, it will traverse the tree of componentsand perform such tasks as converting the values of the components to the proper type, validate the

    components values, and store the components values in backing beans.

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200636

    Codingthe Example Application

    http://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/doc
  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    37/50

    Every JSP page that uses JavaServer Faces technology must include a view tag, which is defined in thecore tag library. The view tag represents the root of the component tree. All JavaServer Facescomponent tags must be included inside the view tag.

    A typical JavaServer Faces page also includes a form in which the user enters some data in input fieldsand clicks a button to submit the form. If the page contains a form, it must also have a form tag.Allcomponents that are part of the form submission must be inside the form tag.

    To add the view and form tags to the page:

    1. After the tag library declarations, add beginning and ending f:view tags:

    2. In between the beginning and ending f:view tags, add beginning and ending h:form tags:

    Adding Output Labels to Display Read-only Content

    One of the more commonly used component tags is the outputText tag, which represents aread-only component that only displays content. The greeting.jsp page contains outputText tagsthat display the welcome message, the instructions, the label for the input component, and Dukescurrent age.

    The outputText tags that display the localized messages reference the messages from the resource

    bundle that you configured previously. The outputText tag that displays Dukes age references theage from the age property ofDukesBDay bean.

    To reference values for display, the outputText tags use the expression language syntax defined bythe unified expression language. The expression language syntax allows you to use the . or []notation to reference objects and their properties. The name by which an expression references anobject is defined in the configuration file. For example, an expression must refer to the WebMessagesresource bundle with the name bundle. For more information on theexpression language, see theExpression Language section of the Introduction to JavaServer Pages chapter of the Java EE tutorial(http://java.sun.com/javaee/5/docs/tutorial/doc).

    While doing thefollowing exercise, you might want to refer to the WebMessages.properties file, theDukesBDay bean, and the faces-config.xml file that you created earlier.

    To reference the read-only values displayed on the greeting page using outputText tags andexpressions, add the following tags:

    1. In between the beginning and ending h:form tags, add an outputText tag that displays Hi. Im

    Duke. Lets see whos older - you or me. and add some h2 tags around it.

    Chapter 3 Creating Your First Java EE Application 37

    Codingthe Example Application

    http://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/dochttp://java.sun.com/javaee/5/docs/tutorial/doc
  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    38/50

    The value attribute of the outputText tag specifies thetext to display. In this case, the valueattribute uses an expression to reference the message stored in the resource bundle, calledbundle, under the key, Welcome.

    2. After the outputText tag you added in the previous step, add an outputText tag that displaysDuke is.Add an extra space between the closing curly brace and the double quote of theexpression so that there will be a space between Duke Is and the text following it on the page:

    3. After the outputText tag you added in the previous step, add an outputText tag that displays

    Dukes age:

    The dukesBDay part of the expression refers to the DukesBDay bean. The age part of theexpression refers to the age property ofDukesBDay bean.

    4. After the outputText tag you added in the previous step, add a paragraph tag and anotheroutputText tag to display the instructions for filling out theform.

    5. After the outputText tag you added in the previous step, add another paragraph tag and anoutputText tag that displays the label for the input component.Add an extra space at the end ofthis expression too:

    Add an Input Component toAccept the Users Birth DateAnother commonly used component tag is the inputText tag. This tag represents a text field, whichaccepts input from the user. The inputText tag also uses expressions to reference values. However,the inputText tag can use theexpressions to set values as well as get them. The inputText tag on thegreeting.jsp page accepts theusers birth date and sets this value into the yourBD property of theDukesBDay bean.

    To add the inputText tag, do the following:

    1. Add a beginning and ending inputText tag, right after the previous outputText tag that youadded and giveit an ID ofuserBirthday:

    Later, well register a converter on this component. Any error messages displayed as a result ofconversion failing will reference this id attribute.

    2. Add to the inputText taga value attribute that references the yourBD property ofDukesBDay:

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200638

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    39/50

    Registering a Converter on the Input Component

    JavaServer Faces technology includes a set of standard converters and validators that you can registeron components in order to convert and validate their data. You register a converter or validator bynesting the tag representing the converter or validator inside the input components tag.

    To add a converter to theinput component discussed in the previous section, do the following:

    1. Add an f:convertDateTime tag inside the inputText tag and specify the acceptable format of

    the input:

    If the user does not enter something that can be converted to a Date type or the date the userentered is not of the specified pattern then a conversion error occurs. The next section describes

    how to create an error message and display it.2. After the ending inputText tag, add an outputText tag that tells the user what the acceptable

    pattern is. Add an extra space in between the double-quote and the pound sign of the expressionso that there will be space between the text field and the text displayed by this outputText tag:

    Adding an Error Message to Display if Conversion Fails

    To specify an error message to be displayed if conversion fails, do thefollowing:

    1. Add a converterMessage attribute to the inputText tag and use it to specify the error message:

    If the conversion of the users input fails, the following message, stored with the DateError key inthe resource bundle will display on the page:

    Please enter the date in the format MM/dd/yyyy.

    2. Add a paragraph tag followedby a message tag to indicate where the error message must appearon thepage, right before the ending form tag:

    Chapter 3 Creating Your First Java EE Application 39

    h b d h l f h h h

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    40/50

    The style attribute indicates the style of the error message. In this case, the error message textwill be red. The for attribute references the ID of the component that generated the error.

    Add a Button for Submitting the FormIn order for the user to submit the form with his or her birth date to the server, he or she needs toclick a button or a hyperlink, thereby causing a form submit.

    To add a button to the page, do the following:

    1. Right before the message tag you added in the previous section, add thefollowing paragraph tagand commandButton tag:

    2. Save the file by selecting File Save from the menu.

    The value attribute indicates the text that is displayed on the button. Again, you could use anexpression to refer to this value. The action attribute indicates a logical outcome, which tells thepage navigation system which page to display next. The following section explains the navigationsystem.

    Defining Page Navigation

    JavaServer Faces technology supports a powerful rule-based system for defining the flow of pages inan application. These rules are defined in the configuration file. To define the page navigation rulesfor the firstcup application, do the following:

    M Defining Page Navigation Rules

    Expand the firstcup-war module in theProjects tree.

    Open the folders Web PagesWEB-INF.

    Double-clickfaces-config.xml.

    Right-click in the editor window andselect JavaServer FacesAdd NavigationRule.

    In the Add Navigation Rule dialog, enter /greeting.jsp in theRule from Viewfield.

    Click Add.

    Repeat steps 4 through 6 except enter/response.jsp in the Rule fromView field.

    Right click in theeditor again andselect JavaServer FacesAdd NavigationCase.

    Select /greeting.jsp from the From Viewmenu.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200640

    E t i th F O t fi ld10

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    41/50

    Enter success in the From Outcome field.

    Select /response.jsp from the To Viewmenu.

    Click Add.

    Repeat steps 8 through 12, except select /response.jsp from the From Viewmenu andselect

    /greeting.jsp from the To View menu.

    You should now see two navigation rules, one that defines how to navigate from greeting.jsp toresponse.jsp, and another one that defines how to navigate from response.jsp to greeting.jsp.The from-view-id tag indicates what the current page is. The to-view-id tag indicates what page to

    go to next.Recall from thesection on adding a button that the commandButton tag has an action attribute thatindicates a logical outcome string. When the button is clicked, the navigation system matches thecurrent page ID and thelogical outcome to a navigation rule. When it finds a match, it will navigateto the page that the rule specifies with its to-view-id tag.

    Save the file by selecting FileSave from the menu bar.

    Creating the response.jsp PageTo create the response.jsp page, do the following:

    1. Rightclick the firstcup-war module.

    2. Select New JSPfromthe popup menu.

    3. Enter response in the JSP File Name field.

    4. Click Finish.

    5. In the response.jsp file, after the html tag, replace anyhead tag in the file with the followinghead tag, which defines the content type:

    Response Page

    6. Remove thebeginning and ending body tags.

    7. Remove JSP Page from the file.

    8. Add the following taglib declarations right after the ending head tag.

    9. After the taglib declarations, add the beginning and ending f:view tags.

    10. In between the beginning and ending f:view tags, add the beginning and ending h:form tags.

    11. In between the beginning and ending h:form tags, add the following outputText tags:

    10

    11

    12

    13

    14

    Chapter 3 Creating Your First Java EE Application 41

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    42/50

    The outputText tags on the response.jsp page use the rendered attribute to control which oneof the tags will actually have their content rendered. Lets take a look at the set ofoutputTexttags:

    The first tag will yield the text You are.

    The rendered attribute of the second outputText tag references an expression that tests if theageDiff property ofDukesBDay is equal to zero. If this expression returns true then the messagereferenced by the tags value attribute will be rendered. This message is the same age as Duke.

    The value attribute of the third tag references the absAgeDiff property ofDukesBDay. Thisproperty holds the absolute value of the age difference. The expressions referenced by therendered attributes of thefourth and fifth tags test whether or not the age difference is equal t o-1 or less than 1 to determine whether the age difference is only one year or more than one yearso that year or years is rendered appropriately. The sixth tag tests ifageDiff is less than zero.If this is true then the absolute value of the age difference is rendered along with the messageyounger than Duke!. So an example message that can be rendered by this group of tags is:

    You are 10 years younger than Duke!

    The last group of tags work similarly to the previous set of tags, except that their renderedattributes test for age differences greater than zero, indicating that the user is older than Duke.

    12. Before the ending tag, add the following paragraph tag and commandButton tag torender a button used for returning to the greeting.jsp page.

    13. Save the file by selecting File Save.

    Building, Packaging, Deploying, and Running thefirstcup EnterpriseApplicationIn this section, you will build the DukesBirthdayBean and the firstcup web client, package them

    into an EAR file, deploy the EAR file to the server, and run theapplication.

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200642

    M Preparing the Deployment Descriptor

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    43/50

    M Preparing the Deployment Descriptor

    In this task, you will remove some extra parameters from the deployment descriptor of the

    firstcup-war module. NetBeans generates these parameters, but we dont need them in our

    example.

    Expand thefirstcup-war modulein the Projects pane.

    Expand the Configuration Files directory.

    Double-clickweb.xml.

    Click General at the top of the editor window.

    Select the plus signnext to Context Parameters.

    From thetable of context parameters, select thefirst context parameter in the table andclick

    Remove.

    Repeat step 6 until all context parameters areremoved.

    Click XML atthe top ofthe editor window.

    Remove the entire welcome-file-list element andall its contents.

    Save the file by selecting FileSave from the menu bar.

    M Building and Packaging the firstcup EnterpriseApplicationWhile performing this task, youll build and package the DukesBirthdayBean enterprise bean and

    the firstcup web client into an EAR file, firstcup.ear, inthe dist directory.

    Select firstcup in the Projects tab.

    Right-clickfirstcup andselect Build Project.

    M Deploying the firstcup EnterpriseApplication

    While performing the previous task, you packaged the DukesBirthdayBean enterprise bean and

    firstcup web client into the firstcup.ear file. Now youll deploy them to theApplication Server.

    Select firstcup in the Projects tab.

    Right-clickfirstcup andselect Deploy Project.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    1

    2

    1

    2

    Chapter 3 Creating Your First Java EE Application 43

    M Running the firstcup Application

    Codingthe Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    44/50

    M Running the firstcup ApplicationThis section describes how to run the firstcup application.

    Launch an internet browser.

    Enter the following URLin the address field of the browser:

    http://localhost:8080/firstcup

    Enter your birth date in the Your birthday text field. Make sure you use the date pattern specified on

    the page:MM/dd/yyyy.

    Click Submit.

    After the response.jsp page is launched, click Back to return to the greeting.jsp page.

    1

    2

    3

    4

    5

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200644

    C H A P T E R 4

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    45/50

    Building, Packaging, and Deploying andRunning the Example Application

    This chapter details how to build, deploy, and run the pre-coded example application included in thefirstcup download bundle using the Ant build tool. If you want to build, deploy, and run theexample that you built in theprevious chapter, please use NetBeans rather than the Ant build tool byfollowing the instructions in the previous chapter.

    Building and Packaging the Example ApplicationThis section describes how to build the example application.

    Building and Packaging the Example Applicationusing ant

    M Building and Packaging firstcup-dukes-age using antAfter you complete this task will build firstcup-dukes-age and create a WAR file,firstcup-dukes-age.war in the dist directory.

    Verify that you have added the Ant build tool that comes with the Application Server to your path.

    The location is the lib/ant/bin directory of your Application Server installation.

    In a terminal, goto /firstcup/example/firstcup-dukes-age.

    If you arebuilding the version of theexample you created in theprevious chapter rather than the

    pre-bundled example code, copy the

    Enter the following command:

    ant

    You should see Build Successful when the command finishes.

    4C H A P T E R 4

    1

    2

    3

    4

    45

    M Deploying firstcup-dukes-age.war using ant

    Deploying the Example Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    46/50

    Deploying firstcup dukes age.war using antThis task gives instructions on deploying firstcup-dukes-age.war using ant.

    Start theApplication Server if you havent already. Refer to your Application Server documentation ifyou are not sure how to start the server.

    Inaterminalgoto /firstcup/example/firstcup-dukes-age.

    Enter the following command:

    ant deploy

    You should see Build Successful when the command finishes.

    M Building and Packaging DukesBirthdayBean and firstcup using ant

    Inaterminal,goto /firstcup/example/firstcup.

    Enter the following command:

    ant

    You should see Build Successful when the command finishes.

    Deploying the Example ApplicationThis section describes how to deploy the example application.

    Deploying the Enterprise Bean and Web ClientThe DukesBirthdayBean enterprise bean and firstcup web client were packaged in firstcup.ear.Now youll deploy them to theApplication Server.

    M Deploying firstcup.ear using antThis task gives instructions on deploying firstcup.ear using ant.

    Inaterminalgoto /firstcup/example/firstcup.

    Enter the following command:

    ant deploy

    You should see Build Successful when the command finishes.

    1

    2

    3

    1

    2

    1

    2

    YourFirstCup: An Introductionto theJava EE Platform October 4, 200646

    Running the Web Client

    Undeployingthe Application

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    47/50

    Running the Web ClientThis section describes how to run the firstcup application.

    To run the application, do the following.

    M Running the firstcup Application

    Launch an internet browser.

    Enter thefollowingURL in theaddress field of the browser:

    http://localhost:8080/firstcup

    Enter yourbirth datein the Your birthday text field. Make sure you use the date pattern specified on

    the page: MM/dd/yyyy.

    Click Submit.

    After the response.jsp page is launched, click Back to return to the greeting.jsp page.

    Undeploying theApplication

    M

    Undeploying withAntGotothe /firstcup/example/firstcup directory.

    Run ant undeploy.

    Gotothe /firstcup/example/firstcup-dukes-age directory.

    Run ant undeploy.

    M Undeploying withAsadmin

    Run asadmin undeploy firstcup-dukes-age.

    Run asadmin undeploy firstcup.

    1

    2

    3

    4

    5

    1

    2

    3

    4

    1

    2

    Chapter 4 Building, P ackaging, and D eploying and Running t he Example Application 47

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    48/50

    48

    C H A P T E R 5

  • 8/7/2019 [Sun Press] Your First Cup - An Introduction to the Java EE Platform

    49/50

    Next Steps

    This chapter points the user at additional resources for learning more about enterprise applicationarchitecture, the Java EE platform, and the Application Server.

    The Ja