JAVA - First Cup

52
Your Fi rst Cup: An Intr oduct ion to the Ja va EE Plat orm Par t No: 821–174 5–10 Augu st 2010 (origi nallypublished2007)

Transcript of JAVA - First Cup

Page 1: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 1/52

Your First Cup: An Introduction to the JavaEE Platorm

Part No: 821–1745–10August 2010 (originallypublished2007)

Page 2: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 2/52

Copyright© 2010, Oracleand/or itsafliates. Allrights reserved.

This sotware and related documentation are provided undera license agreement containingrestrictions on use and disclosure and are protected by intellectualproperty laws. Exceptas expresslypermitted in your license agreementor allowed by law, youmay notuse, copy, reproduce, translate, broadcast, modiy, license,transmit,distribute,exhibit,perorm,publish,or display anypart,in anyorm,or by anymeans. Reverse engineering,disassembly,or decompilation o this sotware,unless required by law or interoperability, is prohibited.

Theinormationcontained hereinis subject to changewithout noticeand is notwarranted to be error-ree. I yound anyerrors,please reportthem to us in writing.

Ithis is sotware or related sotware documentation that is deliveredto theU.S. Government or anyonelicensing it on behalo theU.S. Government, theollowingnotice is applicable:

U.S. GOVERNMENT RIGHTS Programs, sotware, databases, and related documentation and technicaldata deliveredto U.S. Governmentcustomers are“commercial computer sotware” or “commercial technical data” pursuant to the applicableFederalAcquisition Regulation and agency-specic supplementalregulations.As such, theuse, duplication,disclosure,modication, andadaptationshallbe subject to therestrictions andlicensetermsset orth in theapplicableGovernment contract,and, to theextent applicable by thetermso theGovernment contract,the additional rightsset orth in FAR 52.227-19,CommercialComputer Sotware License (December 2007).Oracle America, Inc.,500 Oracle Parkway, Redwood City,CA 94065.

This sotware or hardware is developedor general usein a variety o inormation management applications. Itis notdeveloped or intended oruse in anyinherently dangerousapplications, includingapplications which maycreate a risk o personal injury. I youuse this sotware or hardware in dangerousapplications, then youshall be responsible to take allappropriateail-sae, backup, redundancy, andothermeasuresto ensureits saeuse. OracleCorporationand itsafliatesdisclaimany 

liabilityor anydamagescausedby useo this sotware or hardware in dangerousapplications.Oracleand Java areregistered trademarks o Oracleand/or itsafliates. Other names maybe trademarks o their respective owners.

AMD, Opteron, theAMD logo, andthe AMDOpteron logo aretrademarksor registered trademarks o Advanced Micro Devices. Intel andIntelXeonaretrademarks or registeredtrademarks o IntelCorporation. All SPARC trademarksare used underlicense and are trademarksor registered trademarkso SPARCInternational,Inc. UNIX is a registered trademarklicensed through X/Open Company, Ltd.

This sotware or hardware anddocumentation mayprovide accessto or inormation on content, products,and services rom third parties. OracleCorporationanditsafliates arenot responsible orand expresslydisclaimall warranties o anykind with respect to third-party content, products,and services.Oracle Corporationandits afliates will notbe responsible orany loss, costs,or damages incurred dueto your accessto or useo third-party content, products,or services.

100822@24661

Page 3: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 3/52

Contents

Preace .....................................................................................................................................................5

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

Goals o This Tutorial ............................................................................................................................9

Requirements or This Tutorial ............................................................................................................9

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

2 The Java Platorm, Enterprise Edition ............................................................................................. 13

Dierences between Java EE and Java SE .......................................................................................... 13

The Java Programming Language Platorms ............................................................................ 13

Overview o Enterprise Applications ................................................................................................ 14

Tiered Applications ..................................................................................................................... 15

Java EE Servers ..................................................................................................................................... 17

Java EE Containers ....................................................................................................................... 17

3 CreatingYourFirst Java EE Application ........................................................................................... 19

Architecture o the Example Application ......................................................................................... 19

Tiers in the Example Application ............................................................................................... 20

Java EE Technologies Used in the Example Application ......................................................... 20Coding the Example Application ...................................................................................................... 20

Getting Started ............................................................................................................................. 20

Creating the Web Service Endpoint .......................................................................................... 22

Creating the Enterprise Bean ...................................................................................................... 25

Creating the Web Client .............................................................................................................. 28

Building, Packaging, Deploying, and Running the firstcup Enterprise Application ........ 45

3

Page 4: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 4/52

4 Building, Packaging,and Deployingand Running theExampleApplication ...........................47

Building and Packaging the Example Application .......................................................................... 47

Building and Packaging the Example Application Using Ant ................................................ 47Deploying the Example Application ................................................................................................. 48

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

Running the Web Client ..................................................................................................................... 49

▼ Running the firstcup Application ........................................................................................... 49

Undeploying the Application ............................................................................................................. 49

▼Undeploying with Ant ................................................................................................................. 49

▼Undeploying with asadmin ......................................................................................................... 49

5 NextSteps .............................................................................................................................................51

The Java EE Tutorial ............................................................................................................................ 51

More Inormation on the Java EE Platorm ...................................................................................... 51

Java EE Servers ..................................................................................................................................... 51The Sun Java System Application Server ................................................................................... 51

GlassFish Project .......................................................................................................................... 52

Contents

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)4

Page 5: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 5/52

Preface

This is Your First Cup: AnIntroduction to Java Platorm,Enterprise Edition, a short tutorial or

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

Who Should UseThis Book This tutorial is or novice Java EE developers. You should be amiliar with the Javaprogramming language, particularly the eatures introduced in Java Platorm, Standard Edition5. While amiliarity with enterprise development and Java EE technologies is helpul, thistutorial assumes you are new to developing Java EE applications.

BeoreYou ReadThis Book Beore you start this tutorial, you should:

■ Be amiliar with the Java programming language■ Be able to install sotware on your work machine■ Have a modern web browser installed on your work machine

Related Books and Projects

The ollowing books and projects may be helpul to you in understanding this tutorial:■ The Java EE 5 Tutorial ■ The Sun Java System Application Server documentation set■ The NetBeans IDE documentation set

5

Page 6: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 6/52

Related Third-Party Web Site ReerencesThird-party URLs are reerenced in this document and provide additional, related inormation.

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

Typographic ConventionsThe ollowing table describes the typographic conventions that are used in this book.

TABLEP–1 TypographicConventions

Typeace Meaning Example

AaBbCc123 The names o commands, les, and directories,

and onscreen computer output

Edityour .login le.

Use ls -a to list all les.

machine_name% you have mail.

AaBbCc123 What you type, contrasted with onscreen

computer output

machine_name% su

Password:

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

 flename.

 AaBbCc123 Book titles, new terms, and terms to be

emphasized

Read Chapter 6 in the User's Guide.

A cache isa copy thatis stored

locally.

Do not save the le.

Note: Some emphasized items

appear bold online.

Preface

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)6

Page 7: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 7/52

Shell Prompts in Command ExamplesThe ollowing table shows the deault UNIX system prompt and superuser prompt or the Cshell, Bourne shell, and Korn shell.

TABLEP–2 Shell Prompts

Shell Prompt

C shell machine_name%

C shell or superuser machine_name#

Bourne shell and Korn shell $

Bourne shell and Korn shell or superuser #

Preface

7

Page 8: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 8/52

8

Page 9: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 9/52

Introduction

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

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

■ Understand the basics o tiered applications■ Understand the basics o the Java EE platorm■ Have created a multi-tiered Java EE application■ Have deployed and run your application on a Java EE server■ Know where to go next or more inormation on the Java EE platorm

Requirements orThisTutorial

A Checklist

To complete this tutorial, you need to:■ Get the tutorial bundle■ Get the Java EE 5 Sotware Development Kit■ Get NetBeans IDE (optional)■ Congure your environment

Getting theTutorial Bundle

To get the tutorial bundle, go to the project's java.net (https://firstcup.dev.java.net/

servlets/ProjectDocumentList) site.

1C H A P T E R 1

9

Page 10: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 10/52

GettingtheJavaEE5SDK

To get the Java EE 5 SDK, goto http://java.sun.com/javaee/downloads/previous_u6/

index.jsp.

Getting NetBeans 5.5

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

ConfguringYour EnvironmentOnce you have all the necessary downloads, you must congure the tutorial bundle to reect

your environment.

Building the Examples Using NetBeans IDE

To run the tutorial examples in NetBeans IDE, you must register your Application Server

installation as a NetBeans Server Instance. Follow these instructions to register the ApplicationServer in NetBeans IDE.

1. Select Tools→Server Manager to open the Server Manager dialog.

2. Click Add Server.

3. Under Server, select Sun Java System Application Server and click Next.

4. Under Platorm Location, enter the location o your Application Server installation.

5. Select Register Local Deault Domain and click Next.6. Under Admin Username and Admin Password, enter the admin name and password

created when you installed the Application Server.

7. Click Finish.

Building the Examples on the Command-Line Using Ant

Build properties common to all the examples are specied in the build.properties le in the

tut-install /example/bp-project/ directory. You must create this le beore you can run the

examples. Copy the le build.properties.sample to build.properties and edit it to reect

your environment. The tutorial examples use the Java BluePrints (http://www.oracle.com/

technetwork/java/index-jsp-136701.html) build system and application layout structure.

Requirementsfor This Tutorial

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)10

Page 11: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 11/52

To run the Ant scripts, you must set common build properties in the letut-install /example/bp-project/build.properties as ollows:

Set the javaee.home property to the location o your Application Server installation. Thebuild process uses the javaee.home property to include the libraries in as-install /lib/ in theclasspath. All examples that run on the Application Server include the Java EE library archive, as-install /lib/javaee.jar. in the build classpath. Some examples use additionallibraries in as-install /lib/; the required libraries are enumerated in the individualtechnology chapters.

Note – On Windows, you must escape any backslashes in the javaee.home property withanother backslash or use orward slashes as a path separator. So, i your Application Serverinstallation is C:\Sun\AppServer, you must set javaee.home to javaee.home =

C:\\Sun\\AppServer or javaee.home=C:/Sun/AppServer.

■ Set the firstcup.tutorial.home property to the location o your tutorial. This property isused or Ant deployment and undeployment.

For example, on UNIX:firstcup.tutorial.home=/home/username/firstcup

On Windows:

firstcup.tutorial.home=C:/firstcup

Do not install the tutorial to a location with spaces in the path.

■ I you did not accept the deault values or the admin user and password, set the admin.user

property to the value you specied when you installed the Application Server, and set theadmin user’s password in the admin-password.txt le in thetut-install /example/bp-project/ directory to the value you specied when you installedthe Application Server.

■ I you did not use port 8080, set the javaee.server.port property to the value speciedwhen you installed the Application Server.

Requirementsfor ThisTutorial

Chapter 1 • Introduction 11

Page 12: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 12/52

12

Page 13: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 13/52

The Java Platform, Enterprise Edition

This chapter outlines the eatures o Java EE, how it diers rom Java SE and Java ME, and the

basic concepts behind enterprise application development.

Dierences between Java EE and Java SEJava technology is both a programming language and a platorm. The Java programming

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

platorm is a particular environment in which Java programming language applications run.

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

developers, do not understand how the dierent platorms relate to each other.

The Java Programming Language Platorms

There are three platorms o the Java programming language:

■ Java Platorm, Standard Edition (Java SE)■

Java Platorm, Enterprise Edition (Java EE)■ Java Platorm, Micro Edition (Java ME)

All Java platorms consist o a Java Virtual Machine (VM) and an application programming

interace (API). The Java Virtual Machine is a program, or a particular hardware and sotware

platorm, that runs Java applications. An API is a collection o sotware components that you

can use to create other sotware components or applications. Each Java platorm provides a

 virtual machine and an API, and this allows applications written or that platorm to run on any 

compatible system with all the advantages o the Java programming language:platorm-independence, power, stability, ease-o-development, and security.

2C H A P T E R 2

13

Page 14: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 14/52

 Java SE

When most people think o the Java programming language, they think o the Java SE API. Java

SE's API provides the core unctionality o the Java programming language. It deneseverything rom the basic types and objects o the Java programming language to high-level

classes that are used or networking, security, database access, graphical user interace (GUI)

development, and XML parsing.

In addition to the core API, the Java SE platorm consists o a virtual machine, development

tools, deployment technologies, and other class libraries and toolkits commonly used in Java

applications.

 Java EE

The Java EE platorm is built on top o the Java SE platorm. Java EE provides an API and

runtime environment or developing and running large-scale, multi-tiered, scalable, reliable,

and secure network applications.

 Java ME

The Java ME platorm provides an API and a small-ootprint virtual machine or running Java

programming language applications on small devices, like cellular phones. The API is a subset

o the Java SE API, along with special class libraries useul or small device application

development. Java ME applications are oten clients o Java EE application services.

Overview o Enterprise Applications

This section describes enterprise applications and how they are designed and developed.

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

multi-tiered, scalable, reliable, and secure network applications. A shorthand name or such

applications is “enterprise applications,” so called because these applications are designed to

solve the problems encountered by large enterprises. Enterprise applications are not only useul

or large corporations, agencies, and governments, however. The benets o an enterprise

application are helpul, even essential, or individual developers and small organizations in an

increasingly networked world.

The eatures that make enterprise applications powerul, like security and reliability, oten make

these applications complex. The Java EE platorm is designed to reduce the complexity o 

enterprise application development by providing a development model, API, and runtime

environment that allows developers to concentrate on unctionality.

Overview of EnterpriseApplications

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)14

Page 15: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 15/52

Tiered Applications

In a multi-tiered application, the unctionality o the application is separated into isolated

unctional areas, called tiers. Typically, multi-tiered applications have a client tier, a middle tier,and a data tier (oten called the enterprise inormation systems tier). The client tier consists o aclient program that makes requests to the middle tier. The middle tier's business unctionshandle client requests and process application data, storing it in a permanent datastore in thedata tier.

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

The ClientTier

The client tier consists o application clients that access a Java EE server and that are usually located on a dierent machine rom the server. The clients make requests to the server. Theserver processes the requests and returns a response back to the client. Many dierent types o applications can be Java EE clients, and they are not always, or even oten Java applications.Clients can be a web browser, a stand-alone application, or other servers, and they run on a

dierent machine rom the Java EE server.

TheWebTier

The web tier consists o components that handle the interaction between clients and thebusiness tier. Its primary tasks are the ollowing:

■ Dynamically generate content in various ormats or the client.

Collect input rom users o the client interace and return appropriate results rom thecomponents in the business tier.

■ Control the ow o screens or pages on the client.

■ Maintain the state o data or a user's session.

■ Perorm some basic logic and hold some data temporarily in JavaBeans components.

Java EETechnologies Used in theWeb Tier

The ollowing Java EE technologies are used in the web tier in Java EE applications.

TABLE 2–1 Web Tier Technologies

Technology Purpose

Servlets Java programming language classes that dynamically  

process requests and construct responses, usually or

HTML pages

Overview of Enterprise Applications

Chapter 2 • The Java Platform, Enterprise Edition 15

Page 16: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 16/52

TABLE 2–1 Web Tier Technologies (Continued)

Technology Purpose

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

and dene how dynamic content can be addedto

static pages, such as HTML pages.

JavaServer F aces t echnology A u ser-interace c omponent ramework or w eb

applications that allows you to include UI

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

convert and validate UI component data, save UI

component data to server-side data stores, and

maintain component state.

JavaServerPages StandardTag Library A tag library that encapsulatescoreunctionality 

common to JSPpages

JavaBeans C omponents Objects t hat act a s temporary d ata s tores or the p ages

o an application

The Business Tier

The business tier consists o components that provide the business logic or an application.Business logic is code that provides unctionality to a particular business domain, like thenancial industry, or an e-commerce site. In a properly designed enterprise application, thecore unctionality exists in the business tier components.

Java EETechnologies Used in the BusinessTier

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

■ Enterprise JavaBeans (enterprise bean) components■ JAX-WS web service endpoints■ Java Persistence API entities

The Enterprise Inormation Systems Tier

The enterprise inormation systems (EIS) tier consists o database servers, enterprise resourceplanning systems, and other legacy data sources, like mainrames. These resources typically are

located on a separate machine than the Java EE server, and are accessed by components on thebusiness tier.

Java EETechnologies Used in the EIS Tier

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

■ The Java Database Connectivity API (JDBC)■ The Java Persistence API■ The J2EE Connector Architecture

Overview of EnterpriseApplications

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)16

Page 17: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 17/52

■ The Java Transaction API (JTA)

 Java EE ServersA Java EE server is a server application that the implements the Java EE platorm APIs andprovides the standard Java EE services. Java EE servers are sometimes called application servers,because they allow you to serve application data to clients, much as how web servers serve webpages to web browsers.

Java EE servers host several application component types that correspond to the tiers in a

multi-tiered application. The Java EE server provides services to these components in the ormo a container .

 Java EE Containers

Java EE containers are the interace between the component and the lower-level unctionality provided by the Java EE platorm to support that component. The unctionality o the containeris dened by the Java EE platorm, and is dierent or each component type. Nonetheless, theJava EE server allows the dierent component types to work together to provide unctionality inan enterprise application.

TheWeb Container

The web container is the interace between web components and the web server. A webcomponent can be a servlet, a JSP page, or a JavaServer Faces page. The container manages thecomponent's liecycle, dispatches requests to application components, and provides interacesto context data, such as inormation about the current request.

The Application Client Container

The application client container is the interace between Java EE application clients, which arespecial Java applications that use Java EE server components, and the Java EE server. Theapplication client container runs on the client machine, and is the gateway between the client

application and the Java EE server components that the client uses.

The EJB Container

The EJB container is the interace between enterprise beans, which provide the business logic ina Java EE application, and the Java EE server. The EJB container runs on the Java EE server andmanages the execution o an application's enterprise beans.

Java EE Servers

Chapter 2 • The Java Platform, Enterprise Edition 17

Page 18: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 18/52

18

Page 19: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 19/52

CreatingYour First Java EE Application

This chapter gives an overview o the example application and step-by-step instructions oncoding the example application.

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

DukesAgeService is a JAX-WS endpoint that calculates the age o Duke, the Java mascot. Dukewas born on May 23, 1995, when the rst demo o Java technology was publicly released.

DukesBirthdayBean is a stateless session bean that calculates the dierence between the user'sage and Duke's age.

The firstcup web application is a JavaServer Faces application that accesses DukesAgeService

to display Duke's age, reads in a date provided by the user, accessesDukesBirthdayBean tocalculate who is older, and then displays the dierence in years between the user and Duke.

The web application consists o the ollowing:

greeting.jsp: A JSP page with which a user can enter a date.■ response.jsp: A JSP page that tells the user whether he or she is older or younger than

Duke, based on the date the user entered in the greeting.jsp page.

■ DukesBDay.java: A JavaServer Faces managed bean that denes properties to hold the user'sbirth date, get Duke's current age rom the web service, and get the age dierence betweenthe user and Duke rom the enterprise bean.

■ faces-config.xml: A le used to congure resources or the JavaServer Faces application.

In the case o this application, the le congures a resource bundle containing messages, themanaged bean, DukesBDay, and the page navigation rules.

3C H A P T E R 3

19

Page 20: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 20/52

■ web.xml: The web application's deployment descriptor, which is used to congure certainaspects o a web application when it is installed. In this case, it is used to provide a mappingto the application's FacesServlet instance, which accepts incoming requests, passes them

to the lie cycle or processing, and initializes resources.

Tiers in the Example Application

The example application has one web tier component (the firstcupweb client) and twobusiness tier components (the DukesAgeServiceweb service and theDukesBirthdayBeanenterprise bean). The user's web browser is the client tier component, as it

accesses the rest o the application through the web tier. The example application does notaccess the EIS tier.

 Java EE Technologies Used in the Example Application

The DukesAgeService web service endpoint is a JAX-WS endpoint The DukesBirthdayBean

enterprise bean is a stateless session bean. The firstcupweb client is a JavaServer Faces

application that runs in the web container o the Java EE server.

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

Getting StartedBeore you start coding the example, you need to perorm some set-up tasks:

1. Register the server with your NetBeans IDE.2. Create a directory or the example you will build.3. Speciy some settings.

▼ Register the Server with NetBeans IDE

Launch the NetBeans IDE.

From the menu, selectTools→Server Manager.

Click Add Server.

In the AddServer Instance dialog, select Sun Java System Application Server rom the Server

menu.

1

2

3

4

Coding the Example Application

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)20

C di th E l A li ti

Page 21: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 21/52

(Optional) Enter a name or the server in the Name feld.

Click Next.

Click Browse to fnd the location o the Application Server installation.

Click Next.

Enter the user name you chose when you installed the Application Server in the Admin

Username feld.

Enter the password or this username in the Admin Passwordfeld.

Click Finish.

Click Close.

▼ Create a Directory or the Example

Create another directory at the same level as the example directory and call it myexample.You'll

putthe First Cup application that you build while ollowing this tutorial in this directory.

Copy the entire bp-project older rom the example directory to the myexample directory.

▼ Speciy Some Settings

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

build.properties.

Open the build.properties flein a text editor.

Setthe javaee.home property to the path o your Application Server installation. Use orward

slashes in the path, even i you are on the Windows platorm. For example,you would enter

C:/myServer instead o C:\myServer.

Setthe firstcup.tutorial.home property to the location o your firstcup tutorial

installation, such as C:/firstcup.

Change example to myexample in the path specifed by the javaee.server.passwordfile

property.

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

5

6

7

8

9

10

11

12

1

2

1

2

3

4

5

6

Coding the Example Application

Chapter 3 • Creating Your First Java EE Application 21

Coding the Example Application

Page 22: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 22/52

Set the AS_ADMIN_PASSWORD property to your Application Server password.

Save the build.properties and admin-password.txt flesand close them.

Creating the Web Service EndpointThe DukesAgeService endpoint is a simple web service. Web services are web-basedapplications that use open, XML-based standards and transport protocols to exchange datawith calling clients. Both the requests and responses are sent as XML documents, and areusually sent as HTTP packets. This makes interoperability between dierent systems and

applications easy, as it is not necessary or the client to know the underlying architecture o theserver and vice-versa to make a successul web service call.

Web services are designed to be independent o the client. Typically web service endpoints arepublicly available to a wide variety o clients, and the clients are located throughout the internet.This is called “loose coupling,” as the clients and servers are connected only by the standardXML-based requests and responses. For this reason, DukesAgeService will be developed in itsown application module, and deployed separately rom the DukesBirthdayBean enterprisebean and firstcup web client.

 JAX-WS EndpointsDukesAgeService is a JAX-WS endpoint implemented as a servlet. Servlets are webcomponents that run in the web container.

You'll begin by creating a servlet class, then decorate the class with the @WebServiceannotationto make the class a web service endpoint, and nally you will add the getDukesAge method tocalculate and return Duke's age.

Creating the Endpoint

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

▼ Create the Project in NetBeans IDE

Select File→New Project.

SelectWeb in the Categories pane.

SelectWeb Application in the Projects pane.

Click Next.

Set Project Name to firstcup-dukes-age.

7

8

1

2

3

4

5

Coding the Example Application

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)22

Coding the Example Application

Page 23: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 23/52

Set the Project Location to <INSTALL>/myexample, in which INSTALLis the location o the

firstcup tutorial installation.

Select your Application Server rom the Server menu.

Select Java EE 5 rom the JavaEE Version menu.

Set Context Path to /DukesAgeService

Click Finish.

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

From the Projects pane, right-clickon the index.jsp fle and select Delete. Click Yes in the

dialog.

▼ Create the DukesAge Class

Select File→New File.

Make sure firstcup-dukes-age is selected in the Projectmenu.

Select Java Classes in the Categories pane.

Select Java Class in the File Types pane.

Click Next.

Set Class Name to DukesAge.

Set Package to com.sun.firstcup.webservice.

Click Finish.

You should now see the DukesAge.java le inside the com.sun.firstcup.webservice package

in the Projects pane. The DukesAge.java le should also be open in the editor pane.

▼ Annotate the DukesAge Class as a Web Service

Adda @WebService annotation to the class.

@WebServicepublic class DukesAge {...}

6

7

8

9

10

11

1

2

3

4

5

6

7

8

Coding the Example Application

Chapter 3 • Creating Your First Java EE Application 23

Coding the Example Application

Page 24: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 24/52

▼ Remove the Deault Constructor

Highlight the ollowing deault constructor and delete it, as web service endpoints do not

require a deault constructor.

public DukesAge() {

}

▼ Add the getDukesAge Method

Create a public getDukesAge method with a return type o int.

public int getDukesAge() {

}

Adda @WebMethod annotation to getDukesAge.

@WebMethod

public int getDukesAge() {

}

Add the ollowing 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;

▼ Resolve the Import Statements

Right-click in the Editor.

Select Fix Imports.

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

Select File→Saveromthe menu to savethe fle.

1

2

3

1

2

3

4

g p pp

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)24

Coding the Example Application

Page 25: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 25/52

Building and Deploying theWeb Service

Building DukesAgeService

Select firstcup-dukes-age in the Projects tab.

Right-click firstcup-dukes-age and select Build Project.

▼ Deploying theWeb Service Endpoint

The DukesAgeService endpoint was packaged in a WAR le, firstcup-dukes-age.war. Nowyou'll deploy firstcup-dukes-age.war to the Application Server. This task gives instructionson deploying firstcup-dukes-age.war in NetBeans IDE.

Select firstcup-dukes-age in the Projects tab.

Right-click firstcup-dukes-age and select Deploy Project.

Creating the Enterprise Bean

DukesBirthdayBean is a stateless session bean. Stateless session beans are beans that do notmaintain a conversational state with a client. With stateless session beans the client makesisolated requests that do not depend on any previous state or requests. I you requireconversational state, you use stateul session beans.

To createDukesBirthdayBean

you need to create two Java source les:DukesBirthdayBean

,theenterprise bean class; and DukesBirthdayRemote, the enterprise bean business interace. Theenterprise bean class and the business interace are the only les you need to create anenterprise bean.

Creating DukesBirthdayBean in NetBeans IDE

This section has instructions or creating the enterprise application and DukesBirthdayBean

enterprise bean.

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

Select File→New Project.

Select Enterprise in the Categories pane.

1

2

1

2

1

2

Chapter 3 • Creating Your First Java EE Application 25

Coding the Example Application

Page 26: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 26/52

Select Enterprise Application in the Projects pane.

Click Next.

Set Project Name to firstcup.

Set the Project Location to <INSTALL>/myexample.

By deault the wizard creates an enterprise bean module firstcup-ejb and a webapplication

module firstcup-war. Leave everything in the dialog as it is.

Click Finish.

▼ Setting the Context RootIn this task, you will speciy the context root to identiy the web application in a J2EE server.

Expand the firstcup module in the Projects pane.

In the Confguration Files node, double-click theapplication.xml

fle.

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

Change the context root rom /firstcup-war to /firstcup.

Select File→ Save to save the fle.

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

Select Properties rom the popup menu.

In the Categories tree, select Run.

Change the Context Path to /firstcup.

Click OK.

▼ Creating the DukesBirthdayBean Enterprise Bean ClassNow you'll create the enterprise bean class and business interace source les in NetBeans IDE.The DukesBirthdayRemote business interace is a remote interace.

Select firstcup-ejb project in the Projects tab.

Select File→New File.

3

4

5

6

7

8

1

2

3

4

5

6

7

8

9

10

1

2

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)26

Coding the Example Application

Page 27: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 27/52

Select Enterprise in the Categories pane.

Select Session Bean in the File Types pane.

Click Next.

SetEJBNameto DukesBirthdayBean.

Set the Package name to com.sun.firstcup.ejb.

Set the Session Type to Stateless.

Uncheck Local and check Remote under Create Interace.

Click Finish.

▼ Modiy DukesBirthdayBean.java

Now you'll add the code that calculates the dierence in age in years between Duke and the user.

In DukesBirthdayBean.java, delete the empty deault constructor that NetBeans IDE

generated.

Directly ater the class declaration, paste in the ollowing 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 user’s age from Duke’s ageageDifference = dukesBirthday.get(Calendar.YEAR) -theirBirthday.get(Calendar.YEAR);

logger.info("

Raw ageDifference is:"

+ ageDifference);// Check to see if Duke’s birthday occurs before the user’s. If so,// subtract one from the age differenceif (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {

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

return ageDifference;}

Right-click in the editorwindow and select Fix Imports.

3

4

5

6

7

8

9

10

1

2

3

Chapter 3 • Creating Your First Java EE Application 27

Coding the Example Application

Page 28: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 28/52

Choose the java.util.logging.Logger ully-qualifed name or the Logger class.

Choose the java.util.Date ully-qualifed name or the Date class.

Click OK.

Right-click within the new getAgeDifference method and select EJB Methods→Addto

Remote Interace.

Select File→Save.

▼ Modiy DukesBirthdayRemote.java

Expand the firstcup-ejb module in the Projects pane.

Double-click DukesBirthdayRemote.java under Source Packages→com.sun.firstcup.ejb.

Right-click in the editorwindow and select Fix Imports.

Select java.util.Date as the ully-qualifed class name o the Date class and click OK.

Remove the throws clause rom the method defnition so thatyou are let with int

getAgeDifference(Date date);.

Select File→Save.

Creating the Web Client

To create the web client, you need to perorm the ollowing tasks:

■ Set the firstcup-war module to support JavaServer Faces technology. This will create aweb.xml le that has a mapping to FacesServlet.

■ Create a web service client.

■ Create a resource bundle to hold localized messages used by the JSP pages.■ Congure the resource bundle in the conguration le.

■ Create the DukesBDay managed bean class.

■ Congure DukesBDay in the conguration le.

■ Create the greeting.jsp page.

■ Congure the navigation rules in the conguration le.

■ Create the response.jsp page.

4

5

6

7

8

1

2

3

4

5

6

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)28

Coding the Example Application

Page 29: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 29/52

Setting firstcup-war to Support JavaServer FacesTechnology

All JavaServer Faces applications must include a mapping to the FacesServlet instance in their

deployment descriptors. The FacesServlet instance accepts incoming requests, passes them to

the lie cycle or processing, and initializes resources.

You create the mapping to FacesServlet in the web application's deployment descriptor.

Rather than adding the mapping to the web.xml le directly, NetBeans IDE will create the

web.xml le and perorm the mapping to FacesServlet or you when you speciy that your web

application supports JavaServer Faces technology. To do this, perorm the ollowing task.

▼ Setting firstcup-war to Support JavaServer FacesTechnology

Right-click the firstcup-war module o the firstcup enterprise application in the Projects

pane.

Select Properties rom the popup menu.

Select Frameworks rom the Categories tree.

Click Add.

Select JavaServer Faces rom the list o choices in the dialog.

Click OK.

Change the servlet URL mapping to /firstcupWeb/*.

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

between the application's context path and the page in the URL. Users don't have to include this

path in the URL because firstcup includes an index.jsp page that orwards users to the

greeting.jsp page when they enter the ollowing URL:

http://localhost:8080/firstcup

Deselect the Validate XML checkbox.

Click OK.

The remaining steps tell you how to perorm the orward to greeting.jsp rom the index.jsp

page.

Expand the firstcup-war module in the Projects pane and double-click Web Pages.

Right-click welcomeJSF.jsp, select Delete rom the popup menu, and click Yes in the dialog.

1

2

3

4

5

6

7

8

9

10

11

Chapter 3 • Creating Your First Java EE Application 29

Coding the Example Application

Page 30: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 30/52

Double-click index.jsp.

NetBeans IDE generated this le when you created the firstcup project.

Delete everything on the page.

Enter the ollowing in the index.jsp page:

<jsp:forward page="/firstcupWeb/greeting.jsp"/>

Save the fleby selecting File→ Save rom the menu bar.

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

The firstcup-war web module must consume the firstcup-dukes-age web service in order

to get Duke's current age. For this to happen, you need to create a web service client or the

firstcup-war web module.

▼ Creating a Web Service Client or the firstcup-war Web Module

Select firstcup-war rom the Project pane.

Select File→New File.

SelectWeb Services rom the Categories pane.

SelectWeb Service client rom the File Types pane.

Click Next.

SelectWSDL URL.

Into the WSDL URL feld, enter the ollowing location o the WSDL fle o the web service that the

web service client will consume.

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

Into the Package feld, enter the ollowing package where the client fleswill be generated.

com.sun.firstcup.webservice

Click Finish.

12

13

14

15

1

2

3

4

5

6

7

8

9

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)30

Coding the Example Application

Page 31: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 31/52

Creating a Resource Bundle

In this section, you'll create the resource bundle that contains the static text and error messages

used by the JSP pages. The firstcup client supports both English and Spanish locales.

Thereore you need to create two properties les, each o which will contain the messages or

one o the locales.

▼ Creating a Resource Bundle

Right-click firstcup-war in the Projects pane.

Select New→ File/Folder rom the popup menu.

Select the Other category,then Properties File rom the New File dialog.

In the New Properties File dialog, enter WebMessages in the File Name feld.

In the Folder feld, enter src/java/com/sun/firstcup/web as the location o the fle.

Click Finish.

Ater NetBeans IDE creates the properties fle, enter the ollowing messages or copy them rom

here to the fle:

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=SubmitBack=Back

These messages will be reerenced rom the JSP pages.

Save the fleby selecting File→ Save rom the menu.

To addthe Spanishtranslations o the messages, copy the properties fle

WebMessages_es.properties rom

1

2

3

4

5

6

7

8

9

Chapter 3 • Creating Your First Java EE Application 31

Page 32: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 32/52

Coding the Example Application

Page 33: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 33/52

▼ Adding a Dependency on the Enterprise Bean Module

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

Select Properties.

Select Libraries rom the Categories pane.

Select Add Project.

Navigate to <INSTALL>/myexample/firstcup.

Select the firstcup-ejb project.

Click AddProject JAR Files.

Make sure Build Required Projects is selected.

Click OK.

Creating the DukesBDay Managed Bean Class

The DukesBDay JavaBeans component is a backing bean. A backing bean is a JavaServer Faces

managed bean that acts as a temporary data storage or the values o the components included

on a particular JavaServer Faces page. A managed bean is a JavaBeans component that a

JavaServer Faces application instantiates and stores in scope. The section ollowing this one

describes more about managed beans and how to congure them.

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

ollowing:

■ Create an empty class.

■ Decorate the bean with a web service reerence and an enterprise bean reerence.

Add a property that accesses Duke's current age rom the web service.■ Add a property that accesses the user's current birth date.

■ Add a property that accesses the age dierence rom the DukesBirthdayBean enterprise

bean.

■ Add a property that acceses the absolute value o the age dierence.

1

2

3

4

5

6

7

8

9

Chapter 3 • Creating Your First Java EE Application 33

Coding the Example Application

Page 34: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 34/52

▼ Creating an Empty Class

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

Select New→ JavaClass

Enter DukesBDay in the Class Name feld.

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

Click Finish.

▼ Adding an Enterprise Bean Reerence

Directly ater the class declaration, adda private variable to hold a reerence to the enterprise

bean using the @EJB annotation:

@EJBprivate DukesBirthdayRemote dukesBirthday;

▼ Adding Properties to the BeanDuring this task, you will add the ollowing properties to the DukesBDay bean:

■ age or getting Duke's age rom the web service.■ yourBD to hold the user's birth date.■ ageDiff to get the age dierence rom the enterprise bean.■ absAgeDiff to hold the absolute value o the age dierence.

Ater the dukesBirthday variable declaration, add the ollowing private variables:

private int age;private Date yourBD;private int ageDiff;private int absAgeDiff;

Initialize the variables by adding the ollowing inside the deault constructor:

age = -1;

yourBD = null;ageDiff = -1;absAgeDiff = -1;

▼ Generating the Accessor Methods or the Properties

Right-click in the editor window.

Select Reactor→Encapsulate Fields rom the popup window.

1

2

3

4

5

1

2

1

2

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)34

Coding the Example Application

Page 35: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 35/52

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

setDukesBirthday checkbox.

Click Next.

Click Do Reactoring in the Reactoring pane at the bottom o the IDE window.

You should now see two methods or each property, one to set the value and one to get the valueo the variable or that property.

▼ Getting Duke's Current Age

While perorming this task, you will add some code to the getAge method to access Duke'scurrent age rom the web service.

Expand the firstcup-war module.

Expand theWeb Service Reerences node in the firstcup-war module.

From within theWeb Service Reerences node, go to

DukesAgeService→DukesAgeService→DukesAgePort→getDukesAge.

Drag the getDukesAge operation rom inside the DukesAgePort node to the getAge method in

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

method looks like this:

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 hereint result = port.getDukesAge();System.out.println("Result = "+result);

} catch (Exception ex) {// TODO handle custom exceptions here

}return age;

}

In the getAge method o DukesBDay, change the line int result = port.getDukesAge(); so

that the age variable rather than the result variableissettotheresultothecallto

port.getDukesAge:

age = port.getDukesAge();

Remove the ollowing linerom the getAge method.

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

3

4

5

1

2

3

4

5

6

Chapter 3 • Creating Your First Java EE Application 35

Coding the Example Application

Page 36: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 36/52

▼ Getting the Age Dierence rom the DukesBirthdayBean EnterpriseBean

During this task, you will add code to the getAgeDiff method to get the dierence in agebetween the user's age and Duke's age rom the EJB and to set the absAgeDiff variable to the

absolute value o the age dierence.

Inside the getAgeDiff method, directly beore the return statement, add the ollowing code:

ageDiff = dukesBirthday.getAgeDifference(yourBD);

setAbsAgeDiff(Math.abs(ageDiff));

▼ Adding Import Statements

Right-click in the editor window.

Select Fix Imports rom the popup menu.

Select java.util.Date as the ully qualifed name o the Date class.

Click OK.

▼ Saving DukesBDay

Select File→ Save.

Confguring the DukesBDay Bean in the Confguration File

JavaServer Faces technology allows you to use the conguration le to initialize, congure, and

store managed beans in one o the ollowing scopes:

■ Request, which begins when the user submits a page and ends when the response is

rendered.

Session, which begins when a user rst accesses a page and ends when the user's sessionends, such as when the user's session times out.

■ Application, which lasts until the server stops the application.

Once a bean is congured, a JavaServer Faces page can create and access the bean. In this

section, you'll congure the DukesBDay managed bean.

1

2

3

4

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)36

Coding the Example Application

Page 37: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 37/52

▼ Confguring the DukesBDay Managed Bean

Expand the firstcup-war module in the Projects pane.

Open the olders Web Pages→WEB-INF.

Double-click faces-config.xml.

Right-click in the editorwindow and select JavaServer Faces→AddManaged Bean.

In the AddManaged Bean dialog, enter dukesBDay in the Bean Name feld.

Enter com.sun.firstcup.web.DukesBDay in the Bean Class feld.

Select session rom the scope menu.

Enter DukesBDay backing bean in the Bean Description feld.

Click Add.

You should now see the ollowing in the faces-config.xml le:

<managed-bean><description>DukesBDay backing bean</description><managed-bean-name>dukesBDay</managed-bean-name><managed-bean-class>com.sun.firstcup.web.DukesBDay</managed-bean-class><managed-bean-scope>session</managed-bean-scope>

</managed-bean>

The managed-bean-name element is the name by which the JavaServer Faces pages will reer tothe bean. The managed-bean-class element is the ully-qualied class name o the bean. Themanaged-bean-scope element is the scope in which the bean is saved. You speciy session scopebecause you need an instance o the bean to be available or the entire session so that all pagescan access the values held by the bean.

Select File→ Save to save the fle.

Creating the greeting.jsp Page

The greeting.jsp page includes the welcome message, displays Duke's current age, andaccepts the user's birth date. To create the page, you need to perorm the ollowing tasks:

■ Create an empty JSP page.

■ Declare the JavaServer Faces tag libraries.

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

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

■ Add an input component to accept the birth date.

1

2

3

4

5

6

7

8

9

10

Chapter 3 • Creating Your First Java EE Application 37

Coding the Example Application

Page 38: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 38/52

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

■ Add a custom error message to display i conversion ails.

■ Add a button component so that the user can submit the page.

Creating an Empty JSP Page

To create an empty JSP page, do the ollowing:

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

2. Select New→ JSP rom the popup menu.

3. Enter greeting in the JSP File Name eld.

4. Click Finish.

5. In the greeting.jsp le, ater the html tag, replace any head tag that is already in the pageand add the ollowing one, which denes the content type:

<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Firstcup Greeting Page</title>

</head>

6. Remove the beginning and ending body tags.7. Remove <h1>JSP Page</h1> rom the le.

8. Select File→ Save to save the le.

Declaring the JavaServer FacesTag Libraries

JavaServer Faces technology denes JSP custom tags or representing UI components,converters, validators, and event listeners on a JSP page. A custom tag provides a way to

reerence some Java logic rom a JSP page, thereby reeing page authors rom including the logicin the page and allowing them to reuse the logic by adding the same tag in any o their JSP pages.See the Custom Tags chapter o the Java EE tutorial (http://download.oracle.com/javaee/

5/tutorial/doc/) or more inormation.

Custom tags are dened in tag libraries. JavaServer Faces technology denes two tag libraries.The HTML Render Kit library denes all o the standard UI component tags. Each instance o acomponent tag used on a page represents a corresponding stateul component object on the

server. The core tag library denes tags or representing type converters, data validators, eventlisteners, and other objects and unctions. Similarly to the component tags, each instance o aconverter, 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 ollowing:

1. Ater the ending head tag in greeting.jsp,adda taglib declaration or the HTML render

kit tag library:

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)38

lib fi "h" i "h j j f h l"

Coding the Example Application

Page 39: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 39/52

<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

When using a particular tag rom this tag library, a page author must use the prex h: tospeciy in which tag library the tag is dened. The uri resolves to the tag library denition.

2. Ater the taglib declaration rom the previous step, add a taglib declaration or the coretag library:

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>

Again, when the page author uses a tag rom this library, he or she must use the f: prex tospeciy that the tag is dened in the core tag library.

Adding the f:view and f:form TagsA JavaServer Faces page is represented by a tree o UI components. When a JavaServer Facesimplementation processes the page during the page's lie cycle, it will traverse the tree o components and perorm such tasks as converting the values o the components to the propertype, validate the components' values, and store the components' values in backing beans.

Every JSP page that uses JavaServer Faces technology must include a view tag, which is denedin the core tag library. The view tag represents the root o the component tree. All JavaServer

Faces component tags must be included inside the view tag.

A typical JavaServer Faces page also includes a orm in which the user enters some data in inputelds and clicks a button to submit the orm. I the page contains a orm, it must also have aform tag. All components that are part o the orm submission must be inside the form tag.

To add the viewand orm tags to the page:

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

<f:view></f:view>

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

<f:view><h:form></h:form>

</f:view>

Adding Output Labels to Display Read-only ContentOne o 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

tags that display the welcome message, the instructions, the label or the input component, andDuke's current age.

The outputText tags that display the localized messages reerence the messages rom theresource bundle that you congured previously. The outputText tag that displays Duke's age

reerences the age rom the age property o DukesBDay bean.

Chapter 3 • Creating Your First Java EE Application 39

T l di pl th t tT t t th p i l t d d

Coding the Example Application

Page 40: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 40/52

To reerence values or display, the outputText tags use the expression language syntax dened

by the unied expression language. The expression language syntax allows you to use the . or []

notation to reerence objects and their properties. The name by which an expression reerences

an object is dened in the conguration le. For example, an expression must reer to theWebMessages resource bundle with the name bundle. For more inormation on the expression

language, see the Expression Language section o the Introduction to JavaServer Pages chapter

o the Java EE tutorial (http://download.oracle.com/javaee/5/tutorial/doc/).

While doing the ollowing exercise, you might want to reer to the WebMessages.properties

le, the DukesBDay bean, and the faces-config.xml le that you created earlier.

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

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

I'm Duke. Let's see who's older - you or me.” and add some h2 tags around it.

<h2><h:outputText value="#{bundle.Welcome}"/></h2>

The value attribute o the outputText tag species the text to display. In this case, the value

attribute uses an expression to reerence the message stored in the resource bundle, calledbundle, under the key, Welcome.

2. Ater the outputText tag you added in the previous step, add an outputText tag that

displays “Duke is”. Add an extra space between the closing curly brace and the double quote

o the expression so that there will be a space between “Duke Is” and the text ollowing it on

the page:

<h:outputText value="#{bundle.DukeIs} "/>

3. Ater the outputText tag you added in the previous step, add an outputText tag thatdisplays Duke's age:

<h:outputText value="#{dukesBDay.age}"/>

The dukesBDay part o the expression reers to the DukesBDay bean. The age part o the

expression reers to the age property o DukesBDay bean.

4. Ater the outputText tag you added in the previous step, add a paragraph tag and another

outputText tag to display the instructions or lling out the orm.<p><h:outputText value="#{bundle.Instructions}"/>

5. Ater the outputText tag you added in the previous step, add another paragraph tag and an

outputText tag that displays the label or the input component. Add an extra space at the

end o this expression too:

<p><h:outputText value="#{bundle.YourBD} "/>

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)40

Adding an Input Component to Accept the User's Birth Date

Coding the Example Application

Page 41: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 41/52

Adding an Input Component to Accept the User s Birth Date

Another commonly used component tag is the inputText tag. This tag represents a text eld,which accepts input rom the user. The inputText tag also uses expressions to reerence values.

However, the inputText tag can use the expressions to set values as well as get them. TheinputText tag on the greeting.jsp page accepts the user's birth date and sets this value intothe yourBD property o the DukesBDay bean.

To add the inputText tag, do the ollowing:

1. Add a beginning and ending inputText tag, right ater the previous outputText tag thatyouaddedandgiveitanIDo userBirthday:

<h:inputText id="userBirthday"></h:inputText>

Later, you'll register a converter on this component. Any error messages displayed as a resulto conversion ailing will reerence this id attribute.

2. Addto the inputText tag a value attribute that reerences the yourBD property o DukesBDay:

<h:inputText id="userBirthday"

value="

#{dukesBDay.yourBD}"

></h:inputText>

Registering a Converter on the Input Component

JavaServer Faces technology includes a set o standard converters and validators that you canregister on components in order to convert and validate their data. You register a converter or validator by nesting the tag representing the converter or validator inside the inputcomponent's tag.

To add a converter to the input component discussed in the previous section, do the ollowing:

1. Addan f:convertDateTime tag inside the inputText tag and speciy the acceptable ormato the input:

<h:inputText ...><f:convertDateTime pattern="MM/dd/yyyy" />

</h:inputText>

I the user does not enter something that can be converted to a Date type or the date the userentered is not o the specied pattern then a conversion error occurs. The next sectiondescribes how to create an error message and display it.

2. Ater the ending inputText tag, add an outputText tag that tells the user what theacceptable pattern is. Add an extra space in between the double-quote and the pound sign o the expression so that there will be space between the text eld and the text displayed by thisoutputText tag:

<h:outputText value=" #{bundle.Pattern}"/>

Chapter 3 • Creating Your First Java EE Application 41

Page 42: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 42/52

▼ Defning Page Navigation Rules

Coding the Example Application

Page 43: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 43/52

▼ Defning Page Navigation Rules

Expand the firstcup-war module in the Projects tree.

Open the olders Web Pages→WEB-INF.

Double-click faces-config.xml.

Right-click in the editorwindow and select JavaServer Faces→Add Navigation Rule.

In the AddNavigation Rule dialog, enter /greeting.jsp in the Rule romView feld.

Click Add.

Repeat steps 4 through 6 except enter /response.jsp in the Rule romView feld.

Right-click in the editoragain and select JavaServer Faces→Add Navigation Case.

Select /greeting.jsp rom the From View menu.

Enter success in the From Outcome feld.

Select /response.jsp rom theToView menu.

Click Add.

Repeat steps 8 through 12, except select/response.jsp

rom the FromView menu and select/greeting.jsp rom theToView menu.

You should now see two navigation rules, one that denes how to navigate rom greeting.jsp

to response.jsp, and another one that denes how to navigate rom 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 rom the section on adding a button that the commandButton tag has an action attribute

that indicates a logical outcome string. When the button is clicked, the navigation systemmatches the current page ID and the logical outcome to a navigation rule. When it nds a

match, it will navigate to the page that the rule species with its to-view-id tag.

Savethe fle by selecting File→ Save rom the menu bar.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Chapter 3 • Creating Your First Java EE Application 43

Page 44: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 44/52

The value attribute o the third tag reerences the absAgeDiff property o DukesBDay. This

Coding the Example Application

Page 45: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 45/52

property holds the absolute value o the age dierence. The expressions reerenced by therendered attributes o the ourth and th tags test whether or not the age dierence is equalto -1 or less than –1 to determine whether the age dierence is only one year or more thanone year so that “year” or “years” is rendered appropriately. The sixth tag tests i ageDiff isless than zero. I this is true then the absolute value o the age dierence is rendered alongwith the message “younger than Duke!”. So an example message that can be rendered by thisgroup o tags is:

You are 10 years younger than Duke!

The last group o tags work similarly to the previous set o tags, except that their rendered

attributes test or age dierences greater than zero, indicating that the user is older thanDuke.

12. Beore the ending </h:form> tag, add the ollowing paragraph tag and commandButton tagto render a button used or returning to the greeting.jsp page.

<p><h:commandButton id="back" value="#{bundle.Back}" action="success"/>

13. Save the le by selecting File→ Save.

Building, Packaging, Deploying, and Running thefirstcup Enterprise ApplicationIn this section, you will build the DukesBirthdayBean and the firstcup web client, packagethem into an EAR le, deploy the EAR le to the server, and run the application.

Preparing the Deployment DescriptorIn this task, you will remove some extra parameters rom the deployment descriptor o thefirstcup-war module. NetBeans IDE generates these parameters, but you don't need them inthis example.

Expand the firstcup-war module in the Projects pane.

Expand the Confguration Files directory.

Double-click web.xml.

Click General at the top o the editorwindow.

Select the plus sign next to Context Parameters.

From the table o context parameters, select the frst context parameterin the table and click 

Remove.

1

2

3

4

5

6

Chapter 3 • Creating Your First Java EE Application 45

Repeatstep 6 until all context parameters are removed.7

Coding the Example Application

Page 46: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 46/52

Click XML atthe top o the editor window.

Remove the entire welcome-file-list element and all its contents.

Savethe fle by selecting File→Save rom the menu bar.

▼ Building and Packaging the firstcup Enterprise ApplicationWhile perorming this task, you'll build and package the DukesBirthdayBean enterprise beanand the firstcup web client into an EAR le, firstcup.ear,inthe dist directory.

Select firstcup in the Projects tab.

Right-click firstcup and select Build Project.

▼ Deploying the firstcup Enterprise ApplicationWhile perorming the previous task, you packaged the DukesBirthdayBean enterprise bean andfirstcup web client into the firstcup.ear le. Now you'll deploy them to the ApplicationServer.

Select firstcup in the Projects tab.

Right-click firstcup and select Deploy Project.

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

Launch an internet browser.

Enter the ollowing URL in the address feldo the browser:

http://localhost:8080/firstcup

Enter your birthdate in the Your birthday text feld. Make sure you use the date pattern

specifed on the page: MM/dd/yyyy.

Click Submit.

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

8

9

10

1

2

1

2

1

2

3

4

5

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)46

4C H A P T E R 4

Page 47: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 47/52

Building, Packaging, and Deploying andRunning the Example Application

This chapter details how to build, deploy, and run the pre-coded example application includedin the firstcup download bundle using the Ant build tool. I you want to build, deploy, and runthe example that you built in the previous chapter, please use NetBeans IDE rather than the Antbuild tool by ollowing the instructions in the previous chapter.

Building and Packaging the Example Application

This section describes how to build the example application.

Building and Packaging the Example ApplicationUsing Ant

▼ Building and Packaging firstcup-dukes-age Using Ant

This task builds firstcup-dukes-age and creates a WAR le, firstcup-dukes-age.war, inthe dist directory.

Veriy that you have added the Antbuild tool thatcomes with the Application Server to your

path.The location is the lib/ant/bin directory o your ApplicationServer installation.

Inaterminal,goto <INSTALL>/firstcup/example/firstcup-dukes-age.

Enterthe ollowing command:

ant

You should see Build Successful when the command nishes.

4

1

2

3

47

▼ Deploying firstcup-dukes-age.war Using Ant

Deployingthe Example Application

Page 48: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 48/52

This task gives instructions on deploying firstcup-dukes-age.war using Ant.

Start the Application Server i you haven'talready. Reer to your Application Serverdocumentation i you are not sure how to start the server.

Inaterminalgoto <INSTALL>/firstcup/example/firstcup-dukes-age.

Enterthe ollowing command:

ant deploy

You should seeBuild Successful

when the command nishes.

▼ Building and Packaging DukesBirthdayBean and firstcup Using Ant

Inaterminal,goto <INSTALL>/firstcup/example/firstcup.

Enterthe ollowing command:

antYou should see Build Successful when the command nishes.

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

Deploying the Enterprise Bean and Web Client

The DukesBirthdayBean enterprise bean and firstcup web client were packaged infirstcup.ear. Now you'll deploy them to the Application Server.

▼ Deploying firstcup.ear Using AntThis task gives instructions on deploying firstcup.ear using Ant.

Inaterminalgoto <INSTALL>/firstcup/example/firstcup.

Enterthe ollowing command:

ant deploy

You should see Build Successful when the command nishes.

1

2

3

1

2

1

2

Your First Cup: An Introduction to the JavaEE Platform • August 2010(originally published2007)48

Page 49: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 49/52

Page 50: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 50/52

50

5C H A P T E R 5

Page 51: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 51/52

Next Steps

This chapter points the user at additional resources or learning more about enterpriseapplication architecture, the Java EE platorm, and the Sun Java System Application Server.

The Java EE TutorialThe Java EE Tutorial (http://download.oracle.com/javaee/5/tutorial/doc/) documentsthe technologies that make up the Java EE platorm. The Java EE Tutorial describes each pieceo the platorm in detail, and includes code examples that demonstrate how to use each piece o the platorm.

More Inormation on the Java EE PlatormFor more inormation on the Java EE platorm, see these resources:

■ The Java EEsite (http://www.oracle.com/technetwork/java/javaee/overview/

index.html)■ GlassFish (https://glassfish.dev.java.net)■ The Aquarium (http://blogs.sun.com/theaquarium)

 Java EE ServersJava EE servers are application servers that implement the Java EE platorm technologies.

The Sun Java System Application Server

The Application Server is the reerence implementation o the Java EE platorm APIs.

5

51

Page 52: JAVA - First Cup

8/6/2019 JAVA - First Cup

http://slidepdf.com/reader/full/java-first-cup 52/52