Your First Cup An Introduction to the Java EE Platform

bravesnailsΛογισμικό & κατασκευή λογ/κού

7 Ιουν 2012 (πριν από 5 χρόνια και 4 μήνες)

1.356 εμφανίσεις

Your First Cup:AnIntroductiontotheJava
TM
EEPlatform
Part No:821–1770–14
April 2012
Copyright ©2012,Oracle and/or its affiliates.All rights reserved.
Copyright and License:Your First Cup:AnIntroductionto the Java EEPlatform
This tutorial is a short tutorial introducing beginning Java EEdevelopers to the Java Platform,Enterprise Editionand contains documentation("Tutorial") and
sample code.The"sample code"made available with this Tutorial is licensed separately to you by Oracle under the
Berkeley license
.If you download any such sample
code,you agree to the terms of the Berkeley license.
This Tutorial is provided to you by Oracle under the following license terms containing restrictions onuse and disclosure and is protected by intellectual property
laws.Oracle grants to you a limited,non-exclusive license to use this Tutorial for informationpurposes only,as anaid to learning about the Java EEplatform.Except
as expressly permitted inthese license terms,you may not use,copy,reproduce,translate,broadcast,modify,license,transmit,distribute,exhibit,perform,publish,
or display any part,inany form,or by any means this Tutorial.Reverse engineering,disassembly,or decompilationof this Tutorial is prohibited.
The informationcontained hereinis subject to change without notice and is not warranted to be error-free.If you find any errors,please report themto us inwriting.
If the Tutorial is licensed onbehalf of the U.S.Government,the following notice is applicable:
U.S.GOVERNMENTRIGHTS Programs,software,databases,and related documentationand technical data delivered to U.S.Government customers are
"commercial computer software"or"commercial technical data"pursuant to the applicable Federal AcquisitionRegulationand agency-specific supplemental
regulations.As such,the use,duplication,disclosure,modification,and adaptationshall be subject to the restrictions and license terms set forth inthe applicable
Government contract,and,to the extent applicable by the terms of the Government contract,the additional rights set forth inFAR52.227-19,Commercial
Computer Software License (December 2007).Oracle USA,Inc.,500 Oracle Parkway,Redwood City,CA94065.
This Tutorial is not developed or intended for use inany inherently dangerous applications,including applications which may create a risk of personal injury.If you
use this Tutorial indangerous applications,thenyou shall be responsible to take all appropriate fail-safe,backup,redundancy,and other measures to ensure the safe
use.
THETUTORIALIS PROVIDED"AS IS"WITHOUTWARRANTYOFANYKIND.ORACLEFURTHERDISCLAIMS ALLWARRANTIES,EXPRESS AND
IMPLIED,INCLUDINGWITHOUTLIMITATION,ANYIMPLIEDWARRANTIES OFMERCHANTABILITY,FITNESS FORAPARTICULARPURPOSE
ORNONINFRINGEMENT.
INNOEVENTSHALLORACLEBELIABLEFORANYINDIRECT,INCIDENTAL,SPECIAL,PUNITIVEORCONSEQUENTIALDAMAGES,OR
DAMAGES FORLOSS OFPROFITS,REVENUE,DATAORDATAUSE,INCURREDBYYOUORANYTHIRDPARTY,WHETHERINANACTIONIN
CONTRACTORTORT,EVENIFORACLEHAS BEENADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGES.ORACLE'S ENTIRELIABILITYFOR
DAMAGES HEREUNDERSHALLINNOEVENTEXCEEDONETHOUSANDDOLLARS (U.S.$1,000).
No Technical Support
Oracle's technical support organizationwill not provide technical support,phone support,or updates to you.
Oracle and Java are registered trademarks of Oracle and/or its affiliates.Other names may be trademarks of their respective owners.
The sample code and Tutorial may provide access to or informationoncontent,products,and services fromthird parties.Oracle Corporationand its affiliates are
not responsible for and expressly disclaimall warranties of any kind with respect to third-party content,products,and services.Oracle Corporationand its affiliates
will not be responsible for any loss,costs,or damages incurred due to your access to or use of third-party content,products,or services.
120406@25097
Contents
Preface.....................................................................................................................................................5
1 Introduction...........................................................................................................................................7
Goals of This Tutorial............................................................................................................................7
Requirements for This Tutorial............................................................................................................7
AChecklist.......................................................................................................................................7
2 UnderstandingJavaPlatform,EnterpriseEdition.........................................................................11
Differences betweenJava EEand Java SE..........................................................................................11
The Java Programming Language Platforms............................................................................11
Overviewof Enterprise Applications................................................................................................12
Tiered Applications.....................................................................................................................13
Java EEServers.....................................................................................................................................16
Java EEContainers.......................................................................................................................16
3 CreatingYour First JavaEEApplication...........................................................................................17
Architecture of the Example Applications.......................................................................................17
Tiers inthe Example Applications.............................................................................................18
Java EETechnologies Used inthe Example Applications.......................................................19
Coding the DukesAgeResource Example Application....................................................................19
Getting Started.............................................................................................................................19
Creating the Web Service............................................................................................................19
4 CreatingYour SecondWebApplication...........................................................................................25
Creating the firstcup Project...........................................................................................................25
▼Create the Web ApplicationProject..........................................................................................25
Creating the Java Persistence API Entity..........................................................................................26
3
▼Create the FirstcupUser Entity Class......................................................................................26
▼Add Properties to the FirstcupUser Entity.............................................................................27
▼Add Constructors to the FirstcupUser Entity........................................................................28
▼Add a Named Query to the FirstcupUser Entity....................................................................28
Creating the Enterprise Bean.............................................................................................................29
▼Create the DukesBirthdayBean Enterprise BeanClass...........................................................29
▼Add a Logger Instance to DukesBirthdayBean.java.............................................................30
▼Add a Business Method to DukesBirthdayBean that Gets the Average Age Difference of
firstcup Users............................................................................................................................30
▼Add a Business Method for Calculating the Age Difference BetweenDuke and the User..31
Creating the Web Client.....................................................................................................................32
Creating a Resource Bundle........................................................................................................32
Configuring the Resource Bundle inthe ConfigurationFile..................................................33
Creating the DukesBDay Managed BeanClass..........................................................................34
Creating the Facelets Client........................................................................................................38
Building,Packaging,Deploying,and Running the firstcup Web Application.........................46
▼Build,Package,and Deploy the firstcup Web Application..................................................46
▼Runthe firstcup Application...................................................................................................46
5 Next Steps.............................................................................................................................................49
The Java EETutorial............................................................................................................................49
More Informationonthe Java EEPlatform......................................................................................49
Java EEServers.....................................................................................................................................49
GlassFish Server OpenSource Edition......................................................................................49
Other Java EEServers..................................................................................................................50
Contents
Your First Cup:AnIntroductiontothe Java EE Platform • April 20124
Preface
This is Your First Cup:An Introduction to Java Platform,Enterprise Edition,a short tutorial for
beginning Java EEprogrammers.This tutorial is designed to give you a hands-onlessonon
developing anenterprise applicationfrominitial coding to deployment.
WhoShouldUseThis Book
This tutorial is for novice Java EEdevelopers.You should be familiar with the Java
programming language,particularly the features introduced inJava Platform,Standard Edition
6.While familiarity with enterprise development and Java EEtechnologies is helpful,this
tutorial assumes you are newto developing Java EEapplications.
BeforeYouReadThis Book
Before you start this tutorial,you should:

Be familiar with the Java programming language

Be able to install software onyour work machine

Have a modernweb browser installed onyour work machine
RelatedBooks andProjects
The following books and projects may be helpful to you inunderstanding this tutorial:

The Java EE6 Tutorial

The Oracle GlassFish Server documentationset

The NetBeans IDEdocumentationset
5
RelatedThird-PartyWebSiteReferences
Third-party URLs are referenced inthis document and provide additional,related information.
Note –
Oracle is not responsible for the availability of third-party web sites mentionedinthis
document.Oracle does not endorse and is not responsible or liable for any content,advertising,
products,or other materials that are available onor through such sites or resources.Oracle will
not be responsible or liable for any actual or alleged damage or loss caused or alleged to be
caused by or inconnectionwith use of or reliance onany such content,goods,or services that
are available onor through such sites or resources.
Typographic Conventions
The following table describes the typographic conventions that are used inthis book.
TABLE P–1
TypographicConventions
Typeface Meaning Example
AaBbCc123 The names of commands,files,and directories,
and onscreencomputer 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 output
machine_name% su
Password:
aabbcc123 Placeholder:replace with a real name or value The command to remove a file is rm
filename.
AaBbCc123 Book titles,newterms,and terms to be
emphasized
Read Chapter 6 inthe User's Guide.
Acache is a copy that is stored
locally.
Do not save the file.
Note:Some emphasized items
appear bold online.
Preface
Your First Cup:AnIntroductiontothe Java EE Platform • April 20126
Introduction
Anintroductionto this tutorial.This chapter outlines the goals and the prerequisites for
completing this tutorial.
Goals of ThisTutorial
At the completionof this tutorial,you will:

Understand the basics of tiered applications

Understand the basics of the Java EEplatform

Have created a multi-tiered Java EEapplication

Have deployed and runyour applicationona Java EEserver

Knowwhere to go next for more informationonthe Java EEplatform
Requirements for ThisTutorial
AChecklist
To complete this tutorial,you need to:

Get the Java EE6 Software Development Kit.

Get NetBeans IDEand all necessary plugins.

Configure your environment.

Get the latest updates to the tutorial bundle.
For up-to-the-minute informationonwhich versions of the required software are compatible
with this tutorial,see the
First Cup compatibility page (http://java.net/projects/
firstcup/pages/FirstCupCompatibility)
.
1
C H A P T E R 1
7
GettingtheJavaEE6SDK
To get the Java EE6 SDK,go to
http://www.oracle.com/technetwork/java/javaee/
downloads/
.
GettingNetBeans IDE
To get NetBeans IDE,go to
http://www.netbeans.org/downloads/
,and download the Java
EEdistribution.
ConfiguringYour Environment
Once you have all the necessary downloads,you must configure the tutorial bundle to reflect
your environment.

AddGlassFishServer as aServer inNetBeans IDE
To runthe tutorial examples inNetBeans IDE,you must register your GlassFish Server
installationas a NetBeans server instance.Followthese instructions to register the GlassFish
Server inNetBeans IDE.
FromtheTools menu,chooseServers.
The Servers dialog opens.
ClickAddServer.
Under Server,select GlassFishServer 3+andclickNext.
Under PlatformLocation,browsetoor enter thelocationof your GlassFishServer installation.
ClickNext.
Under Domain,usethedrop-downlist toselect anexistingdomain,typeinthepathtothe
domaindirectlyinthefield,or typethenameof anewdomaintocreate.
Normally,you will select the default domain,domain1.
ClickFinish.
GettingtheLatest Updates totheTutorial
Check for any updates to the tutorial by using the Update Center included with the Java EE6
SDK.
1
2
3
4
5
6
7
Requirements for ThisTutorial
Your First Cup:AnIntroductiontothe Java EE Platform • April 20128

UpdatetheTutorial ThroughtheUpdateCenter
Openthe Update Center and check for any updates to the tutorial.
OpentheServices tabinNetBeans IDEandexpandServers.
Right-clicktheGlassFishServer instanceandselect ViewUpdateCenter todisplaytheUpdate
Tool.
Select AvailableUpdates inthetreetodisplayalist of updatedpackages.
Lookfor updates totheFirst Cupfor JavaEE6(javaee-firstcup-tutorial) package.
If thereis anupdatedversionof First Cup,select First Cup2.1for JavaEE6
(javaee-firstcup-tutorial) andclickInstall.
1
2
3
4
5
Requirements for ThisTutorial
Chapter 1 • Introduction 9
10
UnderstandingJava Platform,Enterprise
Edition
This chapter outlines the features of Java Platform,Enterprise Edition(Java EE),howit differs
fromJava Platform,Standard Edition(Java SE),Java Platform,Micro Edition(Java ME),and
JavaFX,and the basic concepts behind enterprise applicationdevelopment.
Differences betweenJavaEEandJavaSE
Java 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.AJava
platformis a particular environment inwhich Java programming language applications run.
There are several Java platforms.Many developers,evenlong-time Java programming language
developers,do not understand howthe different platforms relate to each other.
TheJavaProgrammingLanguagePlatforms
There are four platforms of the Java programming language:

Java Platform,Standard Edition(Java SE)

Java Platform,Enterprise Edition(Java EE)

Java Platform,Micro Edition(Java ME)

JavaFX
All Java platforms consist of a Java Virtual Machine (VM) and anapplicationprogramming
interface (API).The Java Virtual Machine is a program,for a particular hardware and software
platform,that runs Java technology applications.AnAPI is a collectionof software components
that you canuse to create other software components or applications.Each Java platform
provides a virtual machine and anAPI,and this allows applications writtenfor that platformto
runonany compatible systemwith all the advantages of the Java programming language:
platform-independence,power,stability,ease-of-development,and security.
2
C H A P T E R 2
11
JavaSE
Whenmost people think of the Java programming language,they think of the Java SEAPI.Java
SE's 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 for networking,security,database access,graphical user interface (GUI)
development,and XML parsing.
Inadditionto the core API,the Java SEplatformconsists of a virtual machine,development
tools,deployment technologies,and other class libraries and toolkits commonly used inJava
technology applications.
JavaEE
The Java EEplatformis built ontop of the Java SEplatform.The Java EEplatformprovides an
API and runtime environment for developing and running large-scale,multi-tiered,scalable,
reliable,and secure network applications.
JavaME
The Java MEplatformprovides anAPI and a small-footprint virtual machine for running Java
programming language applications onsmall devices,like mobile phones.The API is a subset of
the Java SEAPI,along with special class libraries useful for small device application
development.Java MEapplications are oftenclients of Java EEplatformservices.
JavaFX
JavaFXis a platformfor creating rich internet applications using a lightweight user-interface
API.JavaFXapplications use hardware-accelerated graphics and media engines to take
advantage of higher-performance clients and a modernlook-and-feel as well as high-level APIs
for connecting to networked data sources.JavaFXapplications may be clients of Java EE
platformservices.
Overviewof EnterpriseApplications
This sectiondescribes enterprise applications and howthey are designed and developed.
As stated above,the Java EEplatformis designed to help developers create large-scale,
multi-tiered,scalable,reliable,and secure network applications.Ashorthand name for 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 useful
for large corporations,agencies,and governments,however.The benefits of anenterprise
applicationare helpful,evenessential,for individual developers and small organizations inan
increasingly networked world.
Overviewof Enterprise Applications
Your First Cup:AnIntroductiontothe Java EE Platform • April 201212
The features that make enterprise applications powerful,like security and reliability,oftenmake
these applications complex.The Java EEplatformis designed to reduce the complexity of
enterprise applicationdevelopment by providing a development model,API,and runtime
environment that allows developers to concentrate onfunctionality.
TieredApplications
Ina multi-tiered application,the functionality of the applicationis separated into isolated
functional areas,called tiers.Typically,multi-tiered applications have a client tier,a middle tier,
and a data tier (oftencalled the enterprise informationsystems tier).The client tier consists of a
client programthat makes requests to the middle tier.The middle tier's business functions
handle client requests and process applicationdata,storing it ina permanent datastore inthe
data tier.
Java EEapplicationdevelopment concentrates onthe middle tier to make enterprise application
management easier,more robust,and more secure.
TheClient Tier
The client tier consists of applicationclients that access a Java EEserver and that are usually
located ona different machine fromthe server.The clients make requests to the server.The
server processes the requests and returns a response back to the client.Many different types of
applications canbe Java EEclients,and they are not always,or evenoftenJava applications.
Clients canbe a web browser,a standalone application,or other servers,and they runona
different machine fromthe Java EEserver.
TheWebTier
The web tier consists of components that handle the interactionbetweenclients and the
business tier.Its primary tasks are the following:

Dynamically generate content invarious formats for the client.

Collect input fromusers of the client interface and returnappropriate results fromthe
components inthe business tier.

Control the flowof screens or pages onthe client.

Maintainthe state of data for a user's session.

Performsome basic logic and hold some data temporarily inJavaBeans components.
JavaEETechnologies UsedintheWebTier
The following Java EEtechnologies are used inthe web tier inJava EEapplications.
Overviewof Enterprise Applications
Chapter 2 • UnderstandingJava Platform,Enterprise Edition 13
TABLE 2–1
Web-Tier Java EETechnologies
Technology Purpose
Servlets Java programming language classes that dynamically
process requests and construct responses,usually for
HTML pages
JavaServer Faces technology Auser-interface component framework for web
applications that allows you to include UI
components (such as fields and buttons) ona page,
convert and validate UI component data,save UI
component data to server-side data stores,and
maintaincomponent state.
JavaServer Faces Facelets technology Facelets applications are a type of JavaServer Faces
applications that use XHTML pages rather thanJSP
pages.
ExpressionLanguage Aset of standard tags used inJSPand Facelets pages to
refer to Java EEcomponents.
JavaServer Pages (JSP) Text-based documents that are compiled into servlets
and define howdynamic content canbe added to
static pages,such as HTML pages.
JavaServer Pages Standard Tag Library Atag library that encapsulates core functionality
commonto JSPpages
JavaBeans Components Objects that act as temporary data stores for the pages
of anapplication
TheBusinessTier
The business tier consists of components that provide the business logic for anapplication.
Business logic is code that provides functionality to a particular business domain,like the
financial industry,or ane-commerce site.Ina properly designed enterprise application,the
core functionality exists inthe business tier components.
JavaEETechnologies UsedintheBusinessTier
The following Java EEtechnologies are used inthe business tier inJava EEapplications:
TABLE 2–2
Business Tier Java EETechnologies
Technology Description
Enterprise JavaBeans (enterprise bean) components Enterprise beans are managed components that
encapsulate the core functionality of anapplication.
Overviewof Enterprise Applications
Your First Cup:AnIntroductiontothe Java EE Platform • April 201214
TABLE 2–2
Business Tier Java EETechnologies (Continued)
Technology Description
JAX-RS RESTful web services AnAPI for creating web services that respond to
HTTPmethods (for example GET or POST methods).
JAX-RS web services are developed according to the
principles of REST,or representational state transfer.
JAX-WS web service endpoints AnAPI for creating and consuming SOAPweb
services.
Java Persistence API entities AnAPI for accessing data inunderlying data stores
and mapping that data to Java programming language
objects.
Java EEmanaged beans Managed components that may provide the business
logic of anapplication,but do not require the
transactional or security features of enterprise beans.
TheEnterpriseInformationSystemsTier
The enterprise informationsystems (EIS) tier consists of database servers,enterprise resource
planning systems,and other legacy data sources,like mainframes.These resources typically are
located ona separate machine thanthe Java EEserver,and are accessed by components onthe
business tier.
JavaEETechnologies UsedintheEISTier
The following Java EEtechnologies are used to access the EIS tier inJava EEapplications:
TABLE 2–3
EIS Tier Java EETechnologies
Technology Description
The Java Database Connectivity API (JDBC) Alow-level API for accessing and retrieving data from
underlying data stores.Acommonuse of JDBCis to
make SQL queries ona particular database.
The Java Persistence API AnAPI for accessing data inunderlying data stores
and mapping that data to Java programming language
objects.The Java Persistence API is a much
higher-level API thanJDBC,and hides the complexity
of JDBCfromthe user.
The Java EEConnector Architecture AnAPI for connecting to other enterprise resources,
like enterprise resource planning or customer
management systemsoftware.
The Java TransactionAPI (JTA) AnAPI for defining and managing transactions,
including distributed transactions or transactions that
cross multiple underlying data sources.
Overviewof Enterprise Applications
Chapter 2 • UnderstandingJava Platform,Enterprise Edition 15
JavaEEServers
AJava EEserver is a server applicationthat the implements the Java EEplatformAPIs and
provides the standard Java EEservices.Java EEservers are sometimes called applicationservers,
because they allowyou to serve applicationdata to clients,much like web servers serve web
pages to web browsers.
Java EEservers host several applicationcomponent types that correspond to the tiers ina
multi-tiered application.The Java EEserver provides services to these components inthe form
of a container.
JavaEEContainers
Java EEcontainers are the interface betweenthe component and the lower-level functionality
provided by the platformto support that component.The functionality of the container is
defined by the platform,and is different for each component type.Nonetheless,the server
allows the different component types to work together to provide functionality inanenterprise
application.
TheWebContainer
The web container is the interface betweenweb components and the web server.Aweb
component canbe a servlet,a JavaServer Faces Facelets page,or a JSPpage.The container
manages the component's lifecycle,dispatches requests to applicationcomponents,and
provides interfaces to context data,such as informationabout the current request.
TheApplicationClient Container
The applicationclient container is the interface betweenJava EEapplicationclients,which are
special Java SEapplications that use Java EEserver components,and the Java EEserver.The
applicationclient container runs onthe client machine,and is the gateway betweenthe client
applicationand the Java EEserver components that the client uses.
TheEJBContainer
The EJBcontainer is the interface betweenenterprise beans,which provide the business logic in
a Java EEapplication,and the Java EEserver.The EJBcontainer runs onthe Java EEserver and
manages the executionof anapplication's enterprise beans.
Java EE Servers
Your First Cup:AnIntroductiontothe Java EE Platform • April 201216
CreatingYour First Java EE Application
This chapter gives anoverviewof the example applications and step-by-step instructions on
coding and running the dukes-age web service example application.
Architectureof theExampleApplications
The example applications consist of four maincomponents:DukesAgeResource,a JAX-RS
RESTful web service;DukesBirthdayBean,anenterprise bean;FirstcupUser,a Java
Persistence API entity;and firstcup,a web applicationcreated with JavaServer Faces Facelets
technology.
DukesAgeResource is a JAX-RS resource that calculates the age of Duke,the Java mascot.Duke
was bornMay 23,1995,whenthe first demo of Java technology was publicly released.
FIGURE 3–1
Architecture of the First CupExample Applications
Java EE Server
dukes-age
Java DB
JAX-RS
Resource
firstcup
Enterprise Beans
Java Persistence API
JavaServer Faces
Application
3
C H A P T E R 3
17
DukesBirthdayBean is a local,no-interface viewstateless sessionbeanthat calculates the
difference betweenthe user's age and Duke's age,and stores the user-submitted data ina Java
Persistence API entity.
FirstcupUser is a Java Persistence API entity that represents a particular user's birthday.It is
stored ina Java DBdatabase table,and managed by DukesBirthdayBean's business methods.
The firstcup web applicationis a JavaServer Faces Facelets applicationthat accesses
DukesAgeResource to display Duke's age,reads ina date provided by the user,accesses
DukesBirthdayBean to calculate who is older,and thendisplays the difference inyears between
the user and Duke and the average age difference of all users.
The firstcup web applicationconsists of the following:

greeting.xhtml:AnXHTML page that uses the JavaServer Faces Facelets tag libraries.
Users cantype their birth date ina field and submit it for comparisonagainst Duke's birth
date.

response.xhtml:AFacelets-enabled XHTML page that tells the user whether he or she is
older or younger thanDuke,based onthe date the user entered inthe greeting.xhtml
page,and displays the average age difference of all users.

DukesBDay.java:AJavaServer Faces managed beanthat defines properties to hold the user's
birth date,get Duke's current age fromthe DukesAgeResource web service,and get the age
difference betweenthe user and Duke fromthe enterprise bean.

web.xml:The web application's deployment descriptor,which is used to configure certain
aspects of a web applicationwhenit is installed.Inthis case,it is used to provide a mapping
to the application's FacesServlet instance,which accepts incoming requests,passes them
to the life cycle for processing,and initializes resources.It also specifies greeting.xhtml as
the welcome file for the application.

WebMessages.properties and WebMessages_es.properties:Java programming language
properties files that containthe localized strings used ingreeting.xhtml and
response.xhtml.By default,the English language strings inWebMessages.properties are
used,but Spanish language strings are also provided inWebMessages_es.properties.

DukesBirthdayBean.java:as described above,the enterprise beanpackaged withinthe
firstcup application.DukesBirthdayBean calculates the difference betweenthe user's
birthday and Duke's birthday.
Tiers intheExampleApplications
The example applications have one web tier component (the firstcup web client),three
business tier components (the DukesAgeResource web service,the FirstcupUser entity,and
the DukesBirthdayBean enterprise bean),and one enterprise informationsystem(EIS) tier (the
data inthe Java DBdatabase table).The user's web browser is the client tier component,as it
accesses the rest of the applicationthrough the web tier.
Architecture of the Example Applications
Your First Cup:AnIntroductiontothe Java EE Platform • April 201218
JavaEETechnologies UsedintheExample
Applications
The DukesAgeResource web service is a JAX-RS resource.The DukesBirthdayBean enterprise
beanis a stateless sessionbean.The FirstcupUser entity is a Java Persistence API entity.The
firstcup web client is a JavaServer Faces applicationthat runs inthe web container of the Java
EEserver.
CodingtheDukesAgeResourceExampleApplication
This sectiondescribes howto code the DukesAgeResource example application,a JAX-RS
RESTful web service endpoint.
GettingStarted
Before you start coding the example,you need to performsome configurationtasks:
1.Register the server with your NetBeans IDEas described in
“Configuring Your
Environment” onpage 8
.
2.Create a directory for the example you will build.

CreateaDirectoryfor theExample
Createanother directoryat thesamelevel as thetut-install/exampledirectory,wheretut-install
is thelocationof thefirstcuptutorial installation,andcall it myexample.
You'll create the applications described inthis tutorial inthis directory.
CreatingtheWebService
The DukesAgeResource endpoint is a simple RESTful web service.RESTstands for
representational state transfer,and software architectures that conformto the principles of
RESTare referred to as RESTful.RESTful web services are web-based applications that use the
HTTPprotocol to access,modify,or delete informationcontained withina resource.ARESTful
web service resource is a source of specific informationidentifiable by a uniformresource
identifier (URI),for example http://example.com/someResource,and may be manipulated by
calling the HTTPprotocol's methods,for example GET or POST.
RESTful web services are oftencontrasted to SOAPweb services (for example,web services
created with the JAX-WS API that is part of Java EE6).Compared to SOAPweb services,
RESTful web services are simpler,as they use HTTPdirectly rather thanas a transport
mechanismfor anunderlying XML document format,and typically offer better performance.

Codingthe DukesAgeResource Example Application
Chapter 3 • CreatingYour First Java EE Application 19
Web services are designed to be independent of their clients.Typically RESTful web services are
publicly 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
HTTP-based requests and responses,and do not need to knoweach other's implementation
details.For this reason,DukesAge will be developed inits ownapplicationmodule,and
deployed separately fromthe DukesBirthdayBean enterprise beanand firstcup web client.
DukesAge could be deployed ona completely different machine without affecting the
functionality of the firstcup web client.
JAX-RSResources
DukesAgeResource is a JAX-RS resource class that responds to HTTPGET requests and returns
a String representing the age of Duke at the time of the request.
To create DukesAgeResource,use the wizard provided by the JAX-RS plug-infor NetBeans IDE
to generate the resource class.This class is annotated with the javax.ws.rs.Path annotation,
which specifies the URL suffix to which the resource will respond.DukesAgeResource has a
single method,getText,annotated with the javax.ws.rs.GET and javax.ws.rs.Produces
annotations.@GET marks the method as a responder to HTTPGET requests,and @Produces
specifies the MIME-type of the response sent back fromgetText to clients.Inthis case,the
MIME-type is text/plain.
CreatingtheEndpoint
InNetBeans IDE,create a web project with a source file called DukesAgeResource.java inthe
firstcup.webservice package using the RESTful Web Service wizard.

CreatetheProject inNetBeans
FromtheFilemenu,chooseNewProject.
IntheCategories pane,select JavaWeb.
IntheProjects pane,select WebApplication.
ClickNext.
IntheProject Namefield,typedukes-age.
IntheProject Locationfield,browsetotut-install/myexample,wheretut-install is thelocationof
thefirstcuptutorial installation.
ClickNext.
Select your GlassFishServer instancefromtheServer menu.
1
2
3
4
5
6
7
8
Codingthe DukesAgeResource Example Application
Your First Cup:AnIntroductiontothe Java EE Platform • April 201220
Select JavaEE6WebfromtheJavaEEVersionmenu.
IntheContext Pathfield,type/DukesAgeService.
ClickFinish.
You should nowsee the module you created inthe Projects tab.
FromtheProjects tab,right-clicktheindex.jspfileandselect Delete.ClickYes inthedialog.

CreatetheDukesAgeResourceClass
Select thedukes-ageproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select WebServices.
IntheFileTypes pane,select RESTful WebServices FromPatterns.
ClickNext.
Under Select Pattern,select SimpleRoot ResourceandclickNext.
IntheResourcePackagefield,typefirstcup.webservice.
InthePathfield,typedukesAge.
IntheClass Namefield,typeDukesAgeResource.
FromtheMIMETypemenu,select text/plain.
ClickFinish.
IntheRESTResources Configurationdialog,uncheckAddJerseyLibraryandclickOK.
You should nowsee the DukesAgeResource.java file inside the firstcup.webservice package
inthe Projects tab.The DukesAgeResource.java file should also be openinthe editor pane.

Configurethedukes-ageWebApplication
Set the default URL that is brought up ina web browser whenyou rundukes-age.
Right-clickthedukes-ageproject intheProjects tabandselect Properties.
IntheCategories pane,clickRun.
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1
2
Codingthe DukesAgeResource Example Application
Chapter 3 • CreatingYour First Java EE Application 21
Set RelativeURL to/resources/dukesAge.
ClickOK.

RemovetheputText Method
The DukesAgeResource JAX-RS resource doesn't respond to HTTPPUT requests.Delete the
generated putText method inDukesAgeResource.
Highlight thefollowinggeneratedJavadoc andmethoddefinitionanddeleteit.
/**
* PUT method for updating or creating an instance of DukesAgeResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("text/plain")
public void putText(String content) {
}

Implement thegetText Method
Add code to DukesAgeResource.getText that calculates Duke's age at the time of the request.
To do this,use the java.util.Calendar and java.util.GregorianCalendar classes to create
anobject representing the date May 23,1995,Duke's birthday.Thencreate another Calendar
object representing today's date,and subtract today's year fromDuke's birth year.If today's date
falls before May 23,subtract a year fromthis result.Thenreturnthe result as a String
representation.
Highlight thecurrent codeingetTextandreplaceit withthefollowingcode:
//Create a new Calendar for Duke’s birthday
Calendar dukesBirthday = new GregorianCalendar(1995,Calendar.MAY,23);
//Create a new Calendar for today
Calendar now = GregorianCalendar.getInstance();
//Subtract today’s year from Duke’s birth year,1995
int dukesAge = now.get(Calendar.YEAR) - dukesBirthday.get(Calendar.YEAR);
dukesBirthday.add(Calendar.YEAR,dukesAge);
//If today’s date is before May 23,subtract a year from Duke’s age
if (now.before(dukesBirthday)) {
dukesAge--;
}
//Return a String representation of Duke’s age
return""+ dukesAge;
Right-clickintheeditor windowandselect Format.
Right-clickintheEditor andselect Fix Imports.
FromtheFilemenu,chooseSavetosavethefile.
3
4

1
2
3
4
Codingthe DukesAgeResource Example Application
Your First Cup:AnIntroductiontothe Java EE Platform • April 201222
BuildingandDeployingtheWebService
Build the JAX-RS web applicationand deploy it to your GlassFish Server instance.

BuildandDeploytheWebServiceEndpoint
Compile,package,and deploy dukes-age.war to GlassFish Server.This task gives instructions
ondeploying dukes-age.war inNetBeans IDE.
Right-clickdukes-ageintheProjects tabandselect Run.
After dukes-age.war deploys successfully to GlassFish Server a web browser will load the URL
of the DukesAgeResource path,and you'll see the returned String representing Duke's age.
Output of DukesAgeResource
Here's anexample of the output of DukesAgeResource displayed ina web browser.
16
At this point,you've successfully created,deployed,and runyour first Java EEapplication.Now
you will create a web applicationthat uses this web service data.

Example3–1
Codingthe DukesAgeResource Example Application
Chapter 3 • CreatingYour First Java EE Application 23
24
CreatingYour SecondWebApplication
This chapter gives step-by-step instructions oncoding and running the firstcup web
application,which uses the dukes-age web service described in
Chapter 3,“Creating Your First
Java EEApplication.”
The firstcup web applicationis a more complicated application,and
uses several different Java EEAPIs.
The firstcup example applicationretrieves,or “consumes,” the data fromthe dukes-age web
service.AJavaServer Faces web front-end asks users to enter their birthdays to find out who is
older,the user or Duke.This data is stored ina Java DBdatabase table using the Java Persistence
API.The business logic,which provides the core functionality of the application,is handled by
anenterprise bean.
All the tiers described in
“Tiered Applications” onpage 13
are present inthe firstcup web
application.The web or client tier is the JavaServer Faces front-end.The enterprise information
systems,or EIS,tier is the Java DBdatabase.The business tier is the enterprise bean.
CreatingthefirstcupProject
The firstcup web applicationproject consists of the Java Persistence API entity,the enterprise
bean,and the JavaServer Faces web front-end.

CreatetheWebApplicationProject
Followthese steps to create a newweb applicationproject inNetBeans IDE.
FromtheFilemenu,chooseNewProject.
IntheCategories pane,select JavaWeb.
IntheProjects pane,select WebApplication.
4
C H A P T E R 4
1
2
3
25
ClickNext.
IntheProject Namefield,typefirstcup.
IntheProject Locationfield,browsetotut-install/myexample,wheretut-install is thelocationof
thefirstcuptutorial installation.
ClickNext.
Select your GlassFishServer instancefromtheServer menu.
MakesureJavaEE6Webis selectedintheJavaEEVersionmenu.
ChecktheEnableContexts andDependencyInjectionbox.
IntheContext Pathfield,makes sureit is set to/firstcup.
ClickNext.
Under Frameworks,select JavaServer Faces.
ClickFinish.
FromtheProjects tab,right-clicktheindex.xhtmlfileandselect Delete.ClickYes inthedialog.
CreatingtheJavaPersistenceAPI Entity
The Java Persistence API allows you to create and use Java programming language classes that
represent data ina database table.AJava Persistence API entity is a lightweight,persistent Java
programming language object that represents data ina data store.Entities canbe created,
modified,and removed fromthe data store by calling the operations of the Java Persistence API
entity manager.Entities,or the data encapsulated by the persistent fields or properties of a
entity,canbe queried using the Java Persistence Query Language (JPQL),a language similar to
SQL that operates onentities.
Infirstcup,there is a single entity that defines one query.

CreatetheFirstcupUser EntityClass
The FirstcupUser Java Persistence API entity represents a particular firstcup user,and stores
the user's birthday and the difference inage betweenthe user and Duke.FirstcupUser also
defines a Java Persistence API query used to calculate the average age difference of all users.
4
5
6
7
8
9
10
11
12
13
14
15
Creatingthe Java Persistence API Entity
Your First Cup:AnIntroductiontothe Java EE Platform • April 201226
Select thefirstcupproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select Persistence.
IntheFileTypes pane,select EntityClass.
ClickNext.
IntheClass Namefield,typeFirstcupUser.
InthePackagefield,typefirstcup.entity.
ClickNext.
Select jdbc/__defaultfromtheDataSourcemenu.
For TableGenerationStrategy,select DropandCreate.
ClickFinish.
You should nowsee the FirstcupUser.java file inside the firstcup.entity package inthe
Projects tab.The FirstcupUser.java file should also be openinthe editor pane.

AddProperties totheFirstcupUser Entity
Create the FirstcupUser entity's two properties:birthday,of type java.util.Calendar;and
ageDifference,of type int.
The birthday property must be annotated with the javax.persistence.Temporal annotation
to mark the property as a date field inthe underlying database table.All persistent fields or
properties of type java.util.Calendar or java.util.Date must be annotated with
@Temporal.
InFirstcupUser.java belowtheidfielddefinition,copyandpasteinthefollowingfield
definitions for birthdayandageDifference:
@Temporal(javax.persistence.TemporalType.DATE)
protected Calendar birthday;
protected int ageDifference;
Belowthegetter andsetter methods for theidproperty,copyandpasteinthefollowinggetter
andsetter methods for thebirthdayandageDifferenceproperties:
public Calendar getBirthday() {
return birthday;
1
2
3
4
5
6
7
8
9
10
11
1
2
Creatingthe Java Persistence API Entity
Chapter 4 • CreatingYour SecondWebApplication 27
}
public void setBirthday(Calendar birthday) {
this.birthday = birthday;
}
public int getAgeDifference() {
return ageDifference;
}
public void setAgeDifference(int ageDifference) {
this.ageDifference = ageDifference;
}
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports.

AddConstructors totheFirstcupUser Entity
Create two constructors for FirstcupUser:one that takes no arguments,and another that takes
two arguments.
Belowthefielddefinitions intheFirstcupUserclass,addthefollowingconstructors:.
public FirstcupUser() {
}
public FirstcupUser(Date date,int ageDifference) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
this.setBirthday(cal);
this.setAgeDifference(ageDifference);
}
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports,thenclickOK.

AddaNamedQuerytotheFirstcupUser Entity
Add a JPQL named query to the FirstcupUser entity that returns the average age difference of
all firstcup users.
This query uses the AVG aggregate functionto returnthe average of all the values of the
ageDifference property of the FirstcupUser entities.
Directlybeforetheclass definition,copyandpasteinthefollowingcode:
@NamedQuery(name="findAverageAgeDifferenceOfAllFirstcupUsers",
query="SELECT AVG(u.ageDifference) FROM FirstcupUser u")
3
4
1
2
3
1
Creatingthe Java Persistence API Entity
Your First Cup:AnIntroductiontothe Java EE Platform • April 201228
The @NamedQuery annotationappears just before the class definitionof the entity,and has two
required attributes:name,with the unique name for this query;and query,the JPQL query
definition.
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports.
FromtheFilemenu,chooseSave.
CreatingtheEnterpriseBean
DukesBirthdayBean is a stateless session bean.Stateless sessionbeans are enterprise beans that
do not maintaina conversational state with a client.With stateless sessionbeans,the client
makes isolated requests that do not depend onany previous state or requests.If anapplication
requires conversational state,use stateful session beans.
To create DukesBirthdayBean,create one Java class:DukesBirthdayBean,the enterprise bean
class.DukesBirthdayBean is a local enterprise bean that uses a no-interface view,meaning two
things.First,a local enterprise beanis only visible withinthe applicationinwhich it is deployed.
Second,enterprise beans with a no-interface viewdo not need a separate business interface that
the enterprise beanclass implements.The enterprise beanclass is the only coding artifact
needed to create a local,no-interface enterprise bean.
DukesBirthdayBean will be packaged withinthe same WARfile as the Facelets web front-end.

CreatetheDukesBirthdayBeanEnterpriseBeanClass
Followthese steps to create the enterprise beanclass inNetBeans IDE.
Select thefirstcupproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select EnterpriseJavaBeans.
IntheFileTypes pane,select SessionBean.
ClickNext.
IntheEJBNamefield,typeDukesBirthdayBean.
InthePackagefield,typefirstcup.ejb.
2
3
4
1
2
3
4
5
6
7
Creatingthe Enterprise Bean
Chapter 4 • CreatingYour SecondWebApplication 29
MakesureStateless is selectedunder SessionType.
ClickFinish.
You should nowsee the DukesBirthdayBean.java file inside the firstcup.ejb package inthe
Projects tab.The DukesBirthdayBean.java file should also be openinthe editor pane.

AddaLogger InstancetoDukesBirthdayBean.java
Add a java.util.logging.Logger instance to the sessionbeanfor logging events.
Directlyafter theclass declaration,pasteinthefollowingfielddefinition:
private static final Logger logger =
Logger.getLogger("firstcup.ejb.DukesBirthdayBean");
This code creates a logger for the sessionbean.
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports,thenclickOK.

AddaBusiness MethodtoDukesBirthdayBeanthat
Gets theAverageAgeDifferenceof firstcupUsers
Add a business method to the DukesBirthdayBean sessionbeanto call the
findAverageAgeDifferenceOfAllFirstcupUsers named query inFirstcupUser that returns
the average age difference of all users.
Belowtheclass definition,adda@PersistenceContext annotationandfieldof type
EntityManager:
@PersistenceContext
private EntityManager em;
Right-clickintheeditor windowandselect Fix Imports.
Addabusiness methodcalledgetAverageAgeDifference bycopyingandpastingthefollowing
code:
public Double getAverageAgeDifference() {
Double avgAgeDiff =
(Double) em.createNamedQuery("findAverageAgeDifferenceOfAllFirstcupUsers")
.getSingleResult();
logger.info("Average age difference is:"+ avgAgeDiff);
return avgAgeDiff;
}
8
9
1
2
3
1
2
3
Creatingthe Enterprise Bean
Your First Cup:AnIntroductiontothe Java EE Platform • April 201230
The named query inFirstcupUser is called by using the EntityManager's createNamedQuery
method.Because this query returns a single number,the getSingleResult method is called on
the returned Query object.The query returns a Double.
Right-clickintheeditor windowandselect Format.

AddaBusiness Methodfor CalculatingtheAge
DifferenceBetweenDukeandtheUser
Add a business method that calculates the difference inage inyears betweenDuke and the user
and creates a newFirstcupUser entity.
Addabusiness methodcalledgetAgeDifference bycopyingandpastingthefollowingcode:
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 Date
theirBirthday.setTime(date);
//Subtract the user’s age from Duke’s age
ageDifference = 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 difference
if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {
ageDifference--;
}
//create and store the user’s birthday in the database
FirstcupUser user = new FirstcupUser(date,ageDifference);
em.persist(user);
logger.info("Final ageDifference is:"+ ageDifference);
return ageDifference;
}
This method creates the Calendar objects used to calculate the difference inage betweenthe
user and Duke and performs the actual calculationof the difference inage.
Similar to the DukesAgeResource.getText code,getAgeDifference subtracts Duke's birthday
year fromthe user's birthday year to get a rawage difference.If Duke's birthday falls before the
user's,and the rawdifference is more than0,it subtracts one year fromthe age difference.
AnewFirstcupUser entity is created with the user's birthday and age difference,thenstored in
the Java DBdatabase by calling the EntityManager's persist method.
The final age difference is returned as anint.
4
1
Creatingthe Enterprise Bean
Chapter 4 • CreatingYour SecondWebApplication 31
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports,thenOK.
FromtheFilemenu,chooseSave.
CreatingtheWebClient
To create the web client,you need to performthe following tasks:

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

Configure the resource bundle inthe configurationfile.

Create the DukesBDay managed beanclass.

Create the Facelets pages.
CreatingaResourceBundle
Inthis section,you'll create the resource bundle that contains the static text and error messages
used by the Facelets pages.The firstcup client supports both English and Spanish locales.
Therefore you need to create two properties files,each of which will containthe messages for
one of the locales.

CreateaResourceBundle
Right-clickthefirstcupproject intheProjects tab.
Fromthepopupmenu,chooseNew,thenchooseOther.
IntheCategories pane,select Other.
IntheFileTypes pane,select Properties File,thenclickNext.
IntheFileNamefield,typeWebMessages.
IntheFolder field,typesrc/java/firstcup/web as thelocationof thefile.
ClickFinish.
After NetBeans IDEcreates theproperties file,typethefollowingmessages or copythemfrom
heretothefile:
Welcome=Hi.My name is Duke.Let us find out who is older -- you or I.
DukeIs=Duke is
YearsOldToday=years old today.
2
3
4
1
2
3
4
5
6
7
8
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201232
Instructions=Type your birthday and click submit.
YourBD=Your birthday
Pattern=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
AverageAge=The average age difference of all First Cup users is
These messages will be referenced fromthe XHTML pages.
FromtheFilemenu,chooseSave.
ToaddtheSpanishtranslations of themessages,copytheproperties file
WebMessages_es.properties from
tut-install/firstcup/example/firstcup/src/java/com/sun/firstcup/web to
tut-install/firstcup/myexample/firstcup/src/java/firstcup/web.
You cancreate multiple properties files,each with a set of messages for a different locale.By
storing localized static text and messages inresource bundles,you don't need to create a
separate set of XHTML pages for each locale.
ConfiguringtheResourceBundleintheConfiguration
File
To make the resource bundle available to the application,you need to configure it inthe
configurationfile,by performing the following task.

CreateaConfigurationFile
The faces-config.xml deployment descriptor contains configurationsettings for the
JavaServer Faces application.JSF applications don't require a deployment descriptor unless they
use features that canonly be configured infaces-config.xml.Infirstcup,the deployment
descriptor has settings defining the resource bundle that provides localized strings inEnglish
and Spanish.
Select thefirstcupproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select JavaServer Faces.
IntheFileTypes pane,select JSFFaces Configuration.
9
10
1
2
3
4
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 33
ClickNext,thenclickFinish.

ConfiguretheResourceBundle
The firstcup applicationis localized for the English and Spanish languages.JavaServer Faces
applications canautomatically select the proper language based onthe locale of the user's web
browser.Specify the default and supported locales inthe faces-config.xml file.
Withthenewlycreatedfaces-config.xml fileopen,clickXML.
Placethecursor betweentheopeningandclosingfaces-configtags.
Addthefollowing<application>tagtoconfiguretheresourcebundle:
<application>
<resource-bundle>
<base-name>firstcup.web.WebMessages</base-name>
<var>bundle</var>
</resource-bundle>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>es</supported-locale>
</locale-config>
</application>
The base-name element of the resource-bundle element identifies the fully qualified class
name of the resource bundle.The var element identifies the name by which the XHTML pages
will reference the resource bundle.The locale-config element identifies the locales supported
by the resource bundle.
Right-clickintheeditor windowandselect Format.
FromtheFilemenu,chooseSave.
CreatingtheDukesBDayManagedBeanClass
The DukesBDay JavaBeans component is a backing bean.Abacking beanis a JavaServer Faces
managed beanthat acts as a temporary data storage for the values of the components included
ona particular JavaServer Faces page.Amanaged beanis a JavaBeans component that a
JavaServer Faces applicationinstantiates and stores inscope.The sectionfollowing this one
describes more about managed beans and howto configure them.
This sectiondescribes howto create the DukesBDay class.To create the class you need to do the
following:

Create the managed beanclass.

Add a property that stores Duke's current age fromthe JAX-RS web service.

Add a property that stores the user's current birth date.
5
1
2
3
4
5
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201234

Add a property that stores the age difference fromthe DukesBirthdayBean enterprise bean.

Add a property that stores the absolute value of the age difference.

Add a property that stores the average age difference of all users.

Add a method that calls DukesBirthdaybean.getAgeDifference,sets the absolute age
difference,and forwards the user to the display page.

CreatetheManagedBeanClass
Create a JavaServer Faces managed beanclass that will subsequently be modified.
Right-clickthefirstcup.webpackageintheProjects tab.
Fromthepopupmenu,chooseNew,thenchooseOther.
IntheCategories pane,select JavaServer Faces.
IntheFileTypes pane,select JSFManagedBean,thenclickNext.
IntheClass Namefield,typeDukesBDay.
InthePackagefield,select firstcup.web.
Select sessionfromtheScopemenu.
ClickFinish.
You should nowsee the DukesBDay.java file inside the firstcup.web package inthe Projects
tab.The DukesBDay.java file should also be openinthe editor pane.
Intheeditor pane,findthe@Namedannotationandmodifythevalueattribute,withthevalue
DukesBDay.Theresultingcodeshouldlooklikethis:
@Named(value ="DukesBDay")

AddanEnterpriseBeanReference
Add a javax.ejb.EJB annotationto inject a reference to the DukesBirthdayBean enterprise
bean.This sessionbeanwill be called fromthe methods inDukesBDay.
Right-clickintheeditor windowinsidetheclass andselect Insert Code,thenselect Call
EnterpriseBean.
1
2
3
4
5
6
7
8
9
1
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 35
IntheCall EnterpriseBeandialog,expandthefirstcupapplication,select
DukesBirthdayBean,andclickOK.
The following field will be added:
@EJB
private DukesBirthdayBean dukesBirthdayBean;

AddProperties totheBean
During this task,you will add the following properties to the DukesBDay bean:

age for getting Duke's age fromthe web service

yourBD to hold the user's birth date

ageDiff to get the age difference fromthe enterprise bean

absAgeDiff to hold the absolute value of the age difference

averageAgeDifference to hold the average age difference of all users
The getter method for the age property uses the java.net and java.io classes to create an
HTTPconnectionto the Duke's Age web service and stores the result.
The yourBD property is annotated @NotNull to indicate that this property must be set.The
@NotNull annotationis one of the BeanValidationconstraints.
IntheDukesBDayclass,copyandpastethefollowingfielddefinitions:
protected int age;
@NotNull protected Date yourBD;
protected int ageDiff;
protected int absAgeDiff;
protected Double averageAgeDifference;
private static final Logger logger = Logger.getLogger("firstcup.web.DukesBDay");
Addadefault constructor that sets theinitial values of thefields bycopyingandpastingthe
followingcode:
public DukesBDay() {
age = -1;
yourBD = null;
ageDiff = -1;
absAgeDiff = -1;
averageAgeDifference = -1.0;
}
Addthefollowinggetter andsetter methods for thenewfields bycopyingandpastingthe
followingcode:
public int getAge() {
//Use the java.net.* APIs to access the Duke’s Age RESTful web service
HttpURLConnection connection = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
URL serverAddress = null;
2
1
2
3
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201236
try {
serverAddress = new URL(
"http://localhost:8080/DukesAgeService/resources/dukesAge");
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
//Make the connection to Duke’s Age
connection.connect();
//Read in the response
rd = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine())!= null) {
sb.append(line);
}
//Convert the response to an int
age = Integer.parseInt(sb.toString());
} catch (MalformedURLException e) {
logger.warning("A MalformedURLException occurred.");
e.printStackTrace();
} catch (ProtocolException e) {
logger.warning("A ProtocolException occurred.");
e.printStackTrace();
} catch (IOException e) {
logger.warning("An IOException occurred");
e.printStackTrace();
}
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getYourBD() {
return yourBD;
}
public void setYourBD(Date yourBD) {
this.yourBD = yourBD;
}
public int getAgeDiff() {
return ageDiff;
}
public void setAgeDiff(int ageDiff) {
this.ageDiff = ageDiff;
}
public int getAbsAgeDiff() {
return absAgeDiff;
}
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 37
public void setAbsAgeDiff(int absAgeDiff) {
this.absAgeDiff = absAgeDiff;
}
public Double getAverageAgeDifference() {
return averageAgeDifference;
}
public void setAverageAgeDifference(Double averageAgeDifference) {
this.averageAgeDifference = averageAgeDifference;
}
Right-clickintheeditor windowandselect Format.
Right-clickintheeditor windowandselect Fix Imports,andclickOK.

Get theAgeDifferencefromtheDukesBirthdayBeanEnterpriseBean
During this task,you will create a processBirthday method to get the difference inage between
the user's age and Duke's age fromthe EJB,set the absAgeDiff variable to the absolute value of
the age difference,and set a result string that will forward the user to the display page.
AddaprocessBirthday methodbycopyingandpastingthefollowingcodejust beforetheend
of theclass:
public String processBirthday() {
this.setAgeDiff(dukesBirthdayBean.getAgeDifference(yourBD));
logger.info("age diff from dukesbday"+ ageDiff);
this.setAbsAgeDiff(Math.abs(this.getAgeDiff()));
logger.info("absAgeDiff"+ absAgeDiff);
this.setAverageAgeDifference(dukesBirthdayBean.getAverageAgeDifference());
logger.info("averageAgeDifference"+ averageAgeDifference);
return"/response.xhtml";
}
This method calls the getAgeDifference method of DukesBirthdayBean to get the age
difference and store it inthe ageDiff property,sets the absolute age difference stored inthe
absAgeDiff property,and sets the average age difference stored inthe averageAgeDifference
property.It returns the relative URL of the response page to which the user will be forwarded.
Right-clickintheeditor windowandselect Format.
FromtheFilemenu,chooseSave.
CreatingtheFacelets Client
The Facelets client consists of a resource library,a composite component,and two XHTML files.
4
5
1
2
3
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201238
ResourceLibraries infirstcup
AJavaServer Faces resource library is a collectionof user-created components collected ina
standard locationina web application.Resource libraries are identified according to a resource
identifier,a string that represents a particular resource withina web application.Resources can
be packaged either at the root of the web applicationor onthe web application's classpath.
Aresource packaged inthe web applicationroot must be ina subdirectory of a resources
directory at the web applicationroot.
resources/resource-identifier
Aresource packaged inthe web applicationclasspath must be ina subdirectory of the
META-INF/resources directory withina web application.
META-INF/resources/resource-identifier
Resource identifiers are unique strings that conformto the following format:
[locale-prefix/][library-name/][library-version/]resource-name[/resource-version]
Elements of the resource identifier inbrackets ([]) are optional.Aresource name,identifying a
particular resource (a file or a graphic,for example),is required.In firstcup,a resource library
with the name components is packaged inthe web applicationroot,and this library contains
one resource,a file called inputDate.xhtml.The resource identifier for this resource is
therefore components/inputDate.xhtml,and it is located inthe web applicationroot at
resources/components/inputDate.xhtml.
TheinputDateCompositeComponent
Acomposite component is a set of user-defined JavaServerFaces and Facelets components
located ina resource.Infirstcup,the inputDate.xhtml resource,located inthe components
resource library,is a composite component that contains tags for reading ina date the user
enters ina form.Composite components consist of aninterface definitionand an
implementation.
The interface definitionis specified with the <cc:interface> tag to define which attributes are
exposed to pages that use the composite component.Attributes are identified with the
<cc:attribute> tag.
The inputDate.xhtml interface definitionis as follows.It defines a single attribute,date,that
must be specified inpages that use the inputDate composite component.
<cc:interface>
<cc:attribute name="date"/>
</cc:interface>
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 39
The implementationof the composite component is specified with the <cc:implementation>
tag.The tags withinthe <cc:implementation> are the actual component tags that will be added
to pages that use the composite component.They canbe any HTML Render Kit,JavaServer
Faces,or Facelets tags.The#{cc.attrs.attribute-name} expressionis used to get the value of
the specified attribute fromthe page or component that is using the composite component.
The implementationof the inputDate composite component is as follows.AnHTML input
text component will store the entered text into the date attribute,accessed by the
#{cc.attrs.date} expression.AJavaServer Faces convertDateTime component will convert
the entered text to a date with the formof MM/dd/yyyy (04/13/2009,for example).
<cc:implementation>
<h:inputText value="#{cc.attrs.date}">
<f:convertDateTime pattern="MM/dd/yyyy"/>
</h:inputText>
</cc:implementation>

CreatetheinputDateCompositeComponent
Create the inputDate composite component as a resource inthe components resource library.
Select thefirstcupproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select JavaServer Faces.
IntheFileTypes pane,select JSFCompositeComponent,thenclickNext.
IntheFileNamefield,typeinputDate.
IntheFolder field,typeresources/components,thenclickFinish.
Addthecompositecomponent interfacedefinitionbetweentheopeningandclosing
<cc:interface>tags ininputDate.xhtml:
<cc:interface>
<cc:attribute name="date"/>
</cc:interface>
Addthecompositecomponent implementationbetweentheopeningandclosing
cc:implementation tags:
<cc:implementation>
<h:inputText value="#{cc.attrs.date}">
<f:convertDateTime pattern="MM/dd/yyyy"/>
</h:inputText>
</cc:implementation>
1
2
3
4
5
6
7
8
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201240
Oneachof theother twolines whereerror glyphs appear,press Alt-Enter andselect thelibrary
declarationthat appears.
Right-clickintheeditor windowandselect Format.
FromtheFilemenu,chooseSave.
TheFaceletsWebInterface
The firstcup web applicationinterface has two XHTML files.The greeting.xhtml file
displays Duke's current age and the formwhere the user canenter a birthday.The
response.xhtml file displays the age difference betweenthe user and Duke.
The greeting.xhtml file contains several pieces of the firstcup applicationdetailed
previously.It uses the localized strings contained inWebMessages.properties and
WebMessages_es.properties.It uses the DukesBDay managed beanto call both the
DukesAgeResource JAX-RS web service and the DukesBirthdayBean enterprise bean.It uses
the inputDate composite component to create the input for the user to enter a birthday.
Here's the content of the greeting.xhtml file.
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:fc="http://java.sun.com/jsf/composite/components">
<h:head>
<title>Firstcup Greeting Page</title>
</h:head>
<h:body>
<h:form>
<h2>
<h:outputText value="#{bundle.Welcome}"/>
</h2>
<h:outputText value="#{bundle.DukeIs}"/>
<h:outputText value="#{DukesBDay.age}#{bundle.YearsOldToday}"/>
<p/>
<h:outputText value="#{bundle.Instructions}"/>
<p/>
<h:outputText value="#{bundle.YourBD}"/>
<fc:inputDate id="userBirthday"date="#{DukesBDay.yourBD}"/>
<h:outputText value="#{bundle.Pattern}"/>
<p/>
<h:commandButton value="#{bundle.Submit}"
action="#{DukesBDay.processBirthday}"/>
<p/>
<h:message for="userBirthday"style="color:red"/>
</h:form>
</h:body>
</html>
9
10
11
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 41
The greeting.xhtml file uses the HTML Render Kit and the components resource library tag
libraries.The components tag library has a prefix of fc,and is used to specify the inputDate
composite component in the formbelow.The <fc:inputDate id="userBirthday"
date="#{DukesBDay.yourBD}"/> tag has the required date attribute,and it stores the value in
the yourBD property inthe DukesBDay managed beanby using the EL expression
#{DukesBDay.yourBD}.
The localized strings are referred to by using the EL expressions#{bundle.property-name}.For
example,the <h:outputText value="#{bundle.Welcome}"/> tag will display the following
string inEnglish locales:
Hi.I’m Duke.Let’s find out who’s older -- you or I.
The <h:commandButton> tag creates a Submit buttonand specifies that a successful submission
should render the response.xhtml file by setting the action attribute to
#{DukesBDay.processBirthday}.The processBirthday method returns the value
"/response.xhtml".The action attribute is used to define navigationrules for forms in
Facelets pages.
If the formsubmissionis unsuccessful,a warning message is displayed.This is done with the
<h:message for="userBirthday"style="color:red"/> tag,which is connected to the
inputDate composite component with the id userBirthday.That is,if there's anerror with the
input of the inputDate component,a warning message is displayed.
The response.xhtml file displays the age difference betweenthe user and Duke and the average
age difference of all users so far.Different strings are displayed based onwhether the user is the
same age,younger,or older thanDuke.The text canbe displayed or not based onthe conditions
specified by the rendered attribute of the <h:outputText> tag.The conditions used inthe
rendered attribute are EL language alternatives to the Java programming language conditional
operators to allowXML parsing of the XHTML file.
TABLE 4–1
Conditional Operator ELLanguage Alternatives
Logical Condition JavaProgrammingLanguageConditional Operator EL LanguageAlternative
AND && &&
EQUALS == ==
LESS THAN < lt
GREATERTHAN > gt
Here's the content of the response.xhtml file.
<?xml version=’1.0’ encoding=’UTF-8’?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201242
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Response Page</title>
</h:head>
<h:body>
<h:form>
<h:outputText value="#{bundle.YouAre}"/>
<h:outputText value="#{bundle.SameAge}"
rendered="#{DukesBDay.ageDiff == 0}"/>
<h:outputText value="#{DukesBDay.absAgeDiff}"
rendered="#{DukesBDay.ageDiff lt 0}"/>
<h:outputText value="#{bundle.Year}"
rendered="#{DukesBDay.ageDiff == -1}"/>
<h:outputText value="#{bundle.Years}"
rendered="#{DukesBDay.ageDiff lt -1}"/>
<h:outputText value="#{bundle.Younger}"
rendered="#{DukesBDay.ageDiff lt 0}"/>
<h:outputText value="#{DukesBDay.absAgeDiff}"
rendered="#{DukesBDay.ageDiff gt 0}"/>
<h:outputText value="#{bundle.Year}"
rendered="#{DukesBDay.ageDiff == 1}"/>
<h:outputText value="#{bundle.Years}"
rendered="#{DukesBDay.ageDiff gt 1}"/>
<h:outputText value="#{bundle.Older}"
rendered="#{DukesBDay.ageDiff gt 0}"/>
<p/>
<h:outputText
value="#{bundle.AverageAge}#{DukesBDay.averageAgeDifference}."/>
<p/>
<h:commandButton id="back"value="#{bundle.Back}"action="greeting"/>
</h:form>
</h:body>
</html>
For example,the#{bundle.SameAge} string is displayed if the user and Duke have the same
birthday as specified by the condition#{DukesBDay.ageDiff == 0} in the rendered attribute.
That is,display the following string if the ageDiff property of DukesBDay equals 0:
You are the same age as Duke!
The formalso contains a <h:commandButton> tag that creates a back buttonthat will direct the
user back to the greeting.xhtml page,as specified inthe action attribute.

CreatetheXHTMLFiles
Create the Facelets XHTML files inNetBeans IDE.
Select WebPages under thefirstcupproject intheProjects tab.
FromtheFilemenu,chooseNewFile.
IntheCategories pane,select JavaServer Faces.
1
2
3
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 43
IntheFileTypes pane,select JSFPage,thenclickNext.
IntheFileNamefield,typegreeting,thenclickFinish.
Repeat theprevious steps tocreateanewFacelets filenamedresponse.

Set theWelcomeFileintheweb.xml Deployment Descriptor
Configure the applicationto use greeting.xhtml as the welcome file by modifying web.xml.
Inthefirstcupproject,expandtheConfigurationFiles node,thendouble-clickweb.xml.
ClickPages.
ClickBrowseunder WelcomeFiles,expandWebPages,select greeting.xhtml,andclickSelect
File.
Edit theWelcomeFiles text fieldsothat thefieldlooks likethis:
faces/greeting.xhtml
FromtheFilemenu,chooseSave.

ModifytheXHTMLFiles
Modify greeting.xhtml to include the components tag library.Modify the titles of both files.
Inthefirstcupproject,double-clickgreeting.xhtmlunder WebPages.
Replacethecurrent <html>tagwiththefollowing,whichincludes thecomponentstaglibrary:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:fc="http://java.sun.com/jsf/composite/components">
The components resource library is referred to by the fc prefix.The HTML Render Kit tag
library is also used ingreeting.xhtml.
Modifythetitledirectlyafter the<html>tag.
<h:head>
<title>First Cup Greeting Page</title>
</h:head>
FromtheFilemenu,chooseSave.
Double-clickresponse.xhtmlandmodifythetitleas follows:
<h:head>
<title>Response Page</title>
</h:head>
4
5
6
1
2
3
4
5
1
2
3
4
5
CreatingtheWebClient
Your First Cup:AnIntroductiontothe Java EE Platform • April 201244
FromtheFilemenu,chooseSave.

AddtheFormtogreeting.xhtml
Add the formthat provides the user interface for displaying Duke's age and specifying the user's
birthday.
Inthefirstcupproject,ingreeting.xhtml,replacethetext betweenthe<h:body>and
</h:body>tags withthefollowing:
<h:form>
<h2>
<h:outputText value="#{bundle.Welcome}"/>
</h2>
<h:outputText value="#{bundle.DukeIs}"/>
<h:outputText value="#{DukesBDay.age}#{bundle.YearsOldToday}"/>
<p/>
<h:outputText value="#{bundle.Instructions}"/>
<p/>
<h:outputText value="#{bundle.YourBD}"/>
<fc:inputDate id="userBirthday"date="#{DukesBDay.yourBD}"/>
<h:outputText value="#{bundle.Pattern}"/>
<p/>
<h:commandButton value="#{bundle.Submit}"
action="#{DukesBDay.processBirthday}"/>
<p/>
<h:message for="userBirthday"style="color:red"/>
</h:form>
Right-clickintheeditor windowandselect Format.
FromtheFilemenu,chooseSave.

AddtheFormtoresponse.html
Add a formthat displays the age difference betweenDuke and the user,displays the average age
difference of all users,and allows the user to navigate back to greeting.xhtml.
Inthefirstcupproject,inresponse.xhtml,replacethetext betweenthe<h:body>and
</h:body>tags withthefollowing:
<h:form>
<h:outputText value="#{bundle.YouAre}"/>
<h:outputText value="#{bundle.SameAge}"
rendered="#{DukesBDay.ageDiff == 0}"/>
<h:outputText value="#{DukesBDay.absAgeDiff}"
rendered="#{DukesBDay.ageDiff lt 0}"/>
<h:outputText value="#{bundle.Year}"
rendered="#{DukesBDay.ageDiff == -1}"/>
<h:outputText value="#{bundle.Years}"
rendered="#{DukesBDay.ageDiff lt -1}"/>
<h:outputText value="#{bundle.Younger}"
rendered="#{DukesBDay.ageDiff lt 0}"/>
<h:outputText value="#{DukesBDay.absAgeDiff}"
6
1
2
3
1
CreatingtheWebClient
Chapter 4 • CreatingYour SecondWebApplication 45
rendered="#{DukesBDay.ageDiff gt 0}"/>
<h:outputText value="#{bundle.Year}"
rendered="#{DukesBDay.ageDiff == 1}"/>
<h:outputText value="#{bundle.Years}"
rendered="#{DukesBDay.ageDiff gt 1}"/>
<h:outputText value="#{bundle.Older}"
rendered="#{DukesBDay.ageDiff gt 0}"/>
<p/>
<h:outputText
value="#{bundle.AverageAge}#{DukesBDay.averageAgeDifference}."/>
<p/>
<h:commandButton id="back"value="#{bundle.Back}"action="greeting"/>
</h:form>
Right-clickintheeditor windowandselect Format.
FromtheFilemenu,chooseSave.
Building,Packaging,Deploying,andRunningthefirstcup
WebApplication
Inthis section,you will build the firstcup web application,deploy it to the server,and runthe
application.

Build,Package,andDeploythefirstcupWeb
Application
While performing this task,you'll build and package the DukesBirthdayBean enterprise bean,
the FirstcupUser entity,and the firstcup web client into a WARfile,firstcup.war,inthe
dist directory,thendeploy it to the server.
Select thefirstcupproject intheProjects tab.
Right-clickfirstcupandselect Deploy.

RunthefirstcupApplication
This sectiondescribes howto runthe firstcup application.
Launchawebbrowser.
TypethefollowingURL intheaddress fieldof thebrowser:
http://localhost:8080/firstcup/
2
3
1
2
1
2
Building,Packaging,Deploying,andRunningthe firstcupWebApplication
Your First Cup:AnIntroductiontothe Java EE Platform • April 201246
Typeyour birthdateintheYour birthdaytext field.Makesureyouusethedatepatternspecified
onthepage:MM/dd/yyyy.
ClickSubmit.
After theresponse.xhtmlpageis displayed,clickBacktoreturntothegreeting.xhtmlpage.
Typeadifferent birthdayinthetext fieldandclickSubmit againtoseehowtheaverageageof
First Cupusers changes.
ASuccessful Response Page for firstcup
You are 20 years older than Duke!
The average age difference of all First Cup users is 20.0.
3
4
5
6
Example4–1
Building,Packaging,Deploying,andRunningthe firstcupWebApplication
Chapter 4 • CreatingYour SecondWebApplication 47
48
Next Steps
This chapter points the user at additional resources for learning more about enterprise
applicationarchitecture,the Java EEplatform,and GlassFish Server.
TheJavaEETutorial
The
Java EETutorial (http://docs.oracle.com/javaee/6/tutorial/doc/)
documents the
technologies that make up the Java EEplatform.The Java EETutorial describes each piece of
the platformindetail,and includes code examples that demonstrate howto use each piece of
the platform.
MoreInformationontheJavaEEPlatform
For more informationonthe Java EEplatform,see these resources:

The Java EEPlatformsite (http://www.oracle.com/technetwork/java/javaee/
overview/)

GlassFish (http://glassfish.java.net/)

The Aquarium(http://blogs.oracle.com/theaquarium/)
,a blog about GlassFish and
open-source Java EEprojects
JavaEEServers
Java EEservers are applicationservers that implement the Java EEplatformtechnologies.
GlassFishServer OpenSourceEdition
GlassFish Server OpenSource Editionis the reference implementationof the Java EEplatform
APIs.
5
C H A P T E R 5
49
TheGlassFishProject
The
GlassFish (http://glassfish.java.net/)
project is the open-source basis for GlassFish
Server.
Other JavaEEServers
There are several other popular Java EEservers used by developers and enterprises.

Oracle WebLogic Suite (http://www.oracle.com/
us/products/middleware/application-server/weblogic-suite/)
.

JBoss fromRed Hat (http://www.jboss.org/)
.

Apache Geronimo (http://geronimo.apache.org/)
.

WebSphere software fromIBM(http://www.ibm.com/software/websphere/)
.
Java EE Servers
Your First Cup:AnIntroductiontothe Java EE Platform • April 201250