Professional Documents
Culture Documents
Your First Cup: An Introduction To The Java EE Platform: Part No: 821-1770-11 November 2010
Your First Cup: An Introduction To The Java EE Platform: Part No: 821-1770-11 November 2010
EE Platform
Copyright and License: Your First Cup: An Introduction to the Java EE Platform
This tutorial is a short tutorial introducing beginning Java EE developers to the Java Platform, Enterprise Edition and 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 on use and disclosure and is protected by intellectual property
laws. Oracle grants to you a limited, non-exclusive license to use this Tutorial for information purposes only, as an aid to learning about the Java EE platform. Except
as expressly permitted in these license terms, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish,
or display any part, in any form, or by any means this Tutorial. Reverse engineering, disassembly, or decompilation of this Tutorial is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.
If the Tutorial is licensed on behalf of the U.S. Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are
"commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental
regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable
Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial
Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
This Tutorial is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you
use this Tutorial in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe
use.
THE TUTORIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ORACLE FURTHER DISCLAIMS ALL WARRANTIES, EXPRESS AND
IMPLIED, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
OR NONINFRINGEMENT.
IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR
DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR DATA USE, INCURRED BY YOU OR ANY THIRD PARTY, WHETHER IN AN ACTION IN
CONTRACT OR TORT, EVEN IF ORACLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ORACLE'S ENTIRE LIABILITY FOR
DAMAGES HEREUNDER SHALL IN NO EVENT EXCEED ONE THOUSAND DOLLARS (U.S. $1,000).
No Technical Support
Oracle's technical support organization will 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 information on content, products, and services from third parties. Oracle Corporation and its affiliates are
not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and 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.
101104@24999
Contents
Preface .....................................................................................................................................................5
1 Introduction ...........................................................................................................................................9
Goals of This Tutorial ............................................................................................................................9
Requirements for This Tutorial ............................................................................................................9
A Checklist .......................................................................................................................................9
3
Contents
This is Your First Cup: An Introduction to Java Platform, Enterprise Edition, a short tutorial for
beginning Java EE programmers. This tutorial is designed to give you a hands-on lesson on
developing an enterprise application from initial coding to deployment.
5
Preface
Note – Oracle is not responsible for the availability of third-party web sites mentioned in this
document. Oracle does not endorse and is not responsible or liable for any content, advertising,
products, or other materials that are available on or through such sites or resources. Oracle will
not be responsible or liable for any actual or alleged damage or loss caused or alleged to be
caused by or in connection with use of or reliance on any such content, goods, or services that
are available on or through such sites or resources.
Typographic Conventions
The following table describes the typographic conventions that are used in this book.
AaBbCc123 The names of commands, files, and directories, Edit your .login file.
and onscreen computer output
Use ls -a to list all files.
machine_name% you have mail.
aabbcc123 Placeholder: replace with a real name or value The command to remove a file is rm
filename.
AaBbCc123 Book titles, new terms, and terms to be Read Chapter 6 in the User's Guide.
emphasized
A cache is a copy that is stored
locally.
Do not save the file.
Note: Some emphasized items
appear bold online.
Shell Prompt
C shell machine_name%
7
8
1
C H A P T E R
Introduction
1
An introduction to this tutorial. This chapter outlines the goals and the prerequisites for
completing this tutorial.
A Checklist
To complete this tutorial, you need to:
■ Get the Java EE 6 Software Development Kit.
■ Get NetBeans IDE and all necessary plugins.
■ Configure your environment.
■ Get the latest updates to the tutorial bundle.
For up-to-the-minute information on which versions of the required software are compatible
with this tutorial, see the First Cup 2.0 compatibility page (http://wikis.sun.com/display/
GlassFish/FirstCup2Compatibility).
9
Requirements for This Tutorial
4 Under Platform Location, browse to or enter the location of your GlassFish Server installation.
5 Click Next.
6 Under Domain, use the drop-down list to select an existing domain, type in the path to the
domain directly in the field, or type the name of a new domain to create.
Normally, you will select the default domain, domain1.
7 Click Finish.
2 Right-click the GlassFish Server instance and select View Update Center to display the Update
Tool.
4 Look for updates to the First Cup 2. 0 for Java EE 6 (javaee-firstcup-tutorial) package.
5 If there is an updated version of First Cup 2.0, select First Cup 2. 0 for Java EE 6
(javaee-firstcup-tutorial) and click Install.
Chapter 1 • Introduction 11
12
2
C H A P T E R 2
This chapter outlines the features of Java Platform, Enterprise Edition (Java EE), how it differs
from Java Platform, Standard Edition (Java SE), Java Platform, Micro Edition (Java ME), and
Java FX, and the basic concepts behind enterprise application development.
There are several Java platforms. Many developers, even long-time Java programming language
developers, do not understand how the different platforms relate to each other.
All Java platforms consist of a Java Virtual Machine (VM) and an application programming
interface (API). The Java Virtual Machine is a program, for a particular hardware and software
platform, that runs Java technology applications. An API is a collection of software components
that you can use to create other software components or applications. Each Java platform
provides a virtual machine and an API, and this allows applications written for that platform to
run on any compatible system with all the advantages of the Java programming language:
platform-independence, power, stability, ease-of-development, and security.
13
Overview of Enterprise Applications
Java SE
When most people think of the Java programming language, they think of the Java SE API. Java
SE's API provides the core functionality of the Java programming language. It defines
everything from the 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.
In addition to the core API, the Java SE platform consists of a virtual machine, development
tools, deployment technologies, and other class libraries and toolkits commonly used in Java
technology applications.
Java EE
The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an
API and runtime environment for developing and running large-scale, multi-tiered, scalable,
reliable, and secure network applications.
Java ME
The Java ME platform provides an API and a small-footprint virtual machine for running Java
programming language applications on small devices, like mobile phones. The API is a subset of
the Java SE API, along with special class libraries useful for small device application
development. Java ME applications are often clients of Java EE platform services.
Java FX
Java FX technology is a platform for creating rich internet applications written in Java FX Script.
Java FX Script is a statically-typed declarative language that is compiled to Java technology
bytecode, which can then be run on a Java VM. Applications written for the Java FX platform
can include and link to Java programming language classes, and may be clients of Java EE
platform services.
As stated above, the Java EE platform is designed to help developers create large-scale,
multi-tiered, scalable, reliable, and secure network applications. A shorthand name for such
applications 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 an enterprise
application are helpful, even essential, for individual developers and small organizations in an
increasingly networked world.
The features that make enterprise applications powerful, like security and reliability, often make
these applications complex. The Java EE platform is designed to reduce the complexity of
enterprise application development by providing a development model, API, and runtime
environment that allows developers to concentrate on functionality.
Tiered Applications
In a multi-tiered application, the functionality of the application is separated into isolated
functional areas, called tiers. Typically, multi-tiered applications have a client tier, a middle tier,
and a data tier (often called the enterprise information systems tier). The client tier consists of a
client program that makes requests to the middle tier. The middle tier's business functions
handle client requests and process application data, storing it in a permanent datastore in the
data tier.
Java EE application development concentrates on the middle tier to make enterprise application
management easier, more robust, and more secure.
Technology Purpose
JavaServer Faces Facelets technology Facelets applications are a type of JavaServer Faces
applications that use XHTML pages rather than JSP
pages.
Expression Language A set of standard tags used in JSP and Facelets pages to
refer to Java EE components.
JavaServer Pages (JSP) Text-based documents that are compiled into servlets
and define how dynamic content can be added to
static pages, such as HTML pages.
JavaServer Pages Standard Tag Library A tag library that encapsulates core functionality
common to JSP pages
JavaBeans Components Objects that act as temporary data stores for the pages
of an application
Java EE Servers
A Java EE server is a server application that the implements the Java EE platform APIs and
provides the standard Java EE services. Java EE servers are sometimes called application servers,
because they allow you to serve application data to clients, much like web servers serve web
pages 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 form
of a container.
Java EE Containers
Java EE containers are the interface between the component and the lower-level functionality
provided by the platform to 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 in an enterprise
application.
This chapter gives an overview of the example application and step-by-step instructions on
coding the example application.
Java EE Server
dukes-age firstcup
Enterprise Beans
Java DB
DukesAgeResource is a JAX-RS resource that calculates the age of Duke, the Java mascot. Duke
was born May 23, 1995, when the first demo of Java technology was publicly released.
19
Architecture of the Example Application
DukesBirthdayBean is a local, no-interface view stateless session bean that calculates the
difference between the user's age and Duke's age, and stores the user-submitted data in a Java
Persistence API entity.
FirstcupUser is a Java Persistence API entity that represents a particular user's birthday. It is
stored in a Java DB database table, and managed by DukesBirthdayBean's business methods.
The firstcup web application is a JavaServer Faces Facelets application that accesses
DukesAgeResource to display Duke's age, reads in a date provided by the user, accesses
DukesBirthdayBean to calculate who is older, and then displays the difference in years between
the user and Duke and the average age difference of all users.
Getting Started
Before you start coding the example, you need to perform some configuration tasks:
1. Register the server with your NetBeans IDE as described in “Configuring Your
Environment” on page 10.
2. Create a directory for the example you will build.
● Create another directory at the same level as the tut-install/example directory, where tut-install
is the location of the firstcup tutorial installation, and call it myexample.
You'll create the applications described in this tutorial in this directory.
HTTP-based requests and responses, and do not need to know each other's implementation
details. For this reason, DukesAge will be developed in its own application module, and
deployed separately from the DukesBirthdayBean enterprise bean and firstcup web client.
DukesAge could be deployed on a completely different machine without affecting the
functionality of the firstcup web client.
JAX-RS Resources
DukesAgeResource is a JAX-RS resource class that responds to HTTP GET 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-in for 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 HTTP GET requests, and @Produces
specifies the MIME-type of the response sent back from getText to clients. In this case, the
MIME-type is text/plain.
4 Click Next.
6 In the Project Location field, browse to tut-install/myexample, where tut-install is the location of
the firstcup tutorial installation.
7 Click Next.
11 Click Finish.
You should now see the module you created in the Projects tab.
12 From the Projects tab, right-click the index.jsp file and select Delete. Click Yes in the dialog.
4 In the File Types pane, select RESTful Web Services From Patterns.
5 Click Next.
6 Under Select Pattern, select Simple Root Resource and click Next.
11 Click Finish.
The default URL that is brought up in a web browser when you run dukes-age can also be
configured in NetBeans IDE.
1 Right-click the dukes-age project in the Projects tab and select Properties.
2 Click Libraries.
6 Click OK.
● Highlight the following generated Javadoc and method definition and delete it.
/**
* 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) {
}
1 Highlight the current code in getText and replace it with the following code:
// 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;
15
4 Click Next.
6 In the Project Location field, browse to tut-install/myexample, where tut-install is the location of
the firstcup tutorial installation.
7 Click Next.
11 Click Next.
13 Click Finish.
14 From the Projects tab, right-click the index.xhtml file and select Delete. Click Yes in the dialog.
5 Click Next.
8 Click Next.
11 Click Finish.
You should now see the FirstcupUser.java file inside the firstcup.entity package in the
Projects tab. The FirstcupUser.java file should also be open in the editor pane.
1 With the cursor inside the class, right-click in the editor window and select Insert Code, then
select Add Property.
The Add Property dialog opens.
4 Click the error glyph next to the new birthday field and select Create @Temporal Annotation.
5 Right-click in the editor window inside the class and select Insert Code, then select Add
Property.
1 Right-click in the editor window inside the class and select Insert Code, then select Constructor.
2 Click Generate.
A no-argument constructor is generated.
3 Place the cursor after the no-argument constructor and add the following code to create the
two-argument constructor:
public FirstcupUser(Date date, int ageDifference) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
this.setBirthday(cal);
this.setAgeDifference(ageDifference);
}
6 Select the java.util.Date fully qualified name for the Date class.
7 Click OK.
This query uses the AVG aggregate function to return the average of all the values of the
ageDifference property of the FirstcupUser entities.
1 Directly before the class definition, copy and paste in the following code:
@NamedQuery(name="findAverageAgeDifferenceOfAllFirstcupUsers",
query="SELECT AVG(u.ageDifference) FROM FirstcupUser u")
The @NamedQuery annotation appears just before the class definition of the entity, and has two
required attributes: name, with the unique name for this query; and query, the JPQL query
definition.
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 bean is only visible within the application in which it is deployed.
Second, enterprise beans with a no-interface view do not need a separate business interface that
the enterprise bean class implements. The enterprise bean class is the only coding artifact
needed to create a local, no-interface enterprise bean.
DukesBirthdayBean will be packaged within the same WAR file as the Facelets web front-end.
5 Click Next.
9 Click Finish.
You should now see the DukesBirthdayBean.java file inside the firstcup.ejb package in the
Projects tab. The DukesBirthdayBean.java file should also be open in the editor pane.
4 Select the java.util.logging.Logger fully qualified name for the Logger class.
5 Click OK.
1 Below the class definition, add a @PersistenceContext annotation and field of type
EntityManager:
@PersistenceContext
private EntityManager em;
3 Right-click in the Editor window and select Insert Code, then select Add Business Method.
6 Click OK.
7 Replace the body of the newly created getAverageAgeDifference method with the
highlighted code:
public Double getAverageAgeDifference() {
Double avgAgeDiff = (Double)
em.createNamedQuery("findAverageAgeDifferenceOfAllFirstcupUsers")
.getSingleResult();
1 Right-click in the editor window and select Insert Code, then select Add Business Method.
7 Replace the body of the getAgeDifference method with the following code:
int ageDifference;
Calendar theirBirthday = new GregorianCalendar();
Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
4 In the File Types pane, select Properties File, then click Next.
7 Click Finish.
8 After NetBeans IDE creates the properties file, type the following messages or copy them from
here to the file:
Welcome=Hi. My name is Duke. Let us find out who is older -- you or I.
DukeIs=Duke is
YearsOldToday=years old today.
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 from the XHTML pages.
10 To add the Spanish translations of the messages, copy the properties 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 can create multiple properties files, each with a set of messages for a different locale. By
storing localized static text and messages in resource bundles, you don't need to create a
separate set of XHTML pages for each locale.
use features that can only be configured in faces-config.xml. In firstcup, the deployment
descriptor has settings defining the resource bundle that provides localized strings in English
and Spanish.
2 Place the cursor between the opening and closing faces-config tags.
This section describes how to create the DukesBDay class. To create the class you need to do the
following:
■ Create the managed bean class.
■ Add a property that stores Duke's current age from the JAX-RS web service.
■ Add a property that stores the user's current birth date.
■ Add a property that stores the age difference from the 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.
4 In the File Types pane, select JSF Managed Bean, then click Next.
8 Click Finish.
You should now see the DukesBDay.java file inside the firstcup.web package in the Projects
tab. The DukesBDay.java file should also be open in the editor pane.
9 In the editor pane, find the @ManagedBean annotation and give it a name attribute, with the value
DukesBDay. The resulting code should look like this:
@ManagedBean(name="DukesBDay")
1 Right-click in the editor window inside the class and select Insert Code, then select Call
Enterprise Bean.
2 In the Call Enterprise Bean dialog, expand the firstcup application, select
DukesBirthdayBean, and click OK.
The following field will be added:
@EJB
private DukesBirthdayBean dukesBirthdayBean;
1 Right-click in the Editor window and select Insert Code, then select Add Property.
4 Click OK.
5 Repeat the above steps to create the properties listed in the following table.
yourBD java.util.Date
ageDiff int
absAgeDiff int
averageAgeDifference Double
Note – The java.util.Date and Double data types are not in the menu; you must type them in
the text field.
7 Insert the annotation @NotNull before the definition, so that it looks like this:
@NotNull protected Date yourBD;
8 After the newly created property fields, add the following Logger instance:
private static final Logger logger = Logger.getLogger("firstcup.web.DukesBDay");
12 Select the java.util.logging.Logger fully qualified name for the Logger class.
Use the java.net and java.io classes to create an HTTP connection to the Duke's Age web
service and read in the result.
4 Click OK.
1 Add a processBirthday method by copying and pasting the following code just before the end
of the class:
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 in the ageDiff property, sets the absolute age difference stored in the
absAgeDiff property, and sets the average age difference stored in the averageAgeDifference
property. It returns the relative URL of the response page to which the user will be forwarded.
resources/resource-identifier
META-INF/resources/resource-identifier
Resource identifiers are unique strings that conform to the following format:
[locale-prefix/][library-name/][library-version/]resource-name[/resource-version]
Elements of the resource identifier in brackets ([]) are optional. A resource 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 in the web application root, 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 in the web application root at
resources/components/inputDate.xhtml.
<cc:interface>
<cc:attribute name="date" />
</cc:interface>
The implementation of the composite component is specified with the <cc:implementation>
tag. The tags within the <cc:implementation> are the actual component tags that will be added
to pages that use the composite component. They can be any HTML Render Kit, JavaServer
Faces, or Facelets tags. The #{cc.attrs.attribute-name} expression is used to get the value of
the specified attribute from the page or component that is using the composite component.
The implementation of the inputDate composite component is as follows. An HTML input
text component will store the entered text into the date attribute, accessed by the
#{cc.attrs.date} expression. A JavaServer Faces convertDateTime component will convert
the entered text to a date with the form of 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>
4 In the File Types pane, select JSF Composite Component, then click Next.
7 Add the composite component interface definition between the opening and closing
<cc:interface> tags in inputDate.xhtml:
<cc:interface>
<cc:attribute name="date" />
</cc:interface>
8 Add the composite component implementation between the opening and closing
cc:implementation tags:
<cc:implementation>
<h:inputText value="#{cc.attrs.date}">
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:inputText>
</cc:implementation>
9 If an error glyph appears on the <html> tag, click the error glyph and select Disable HTML
error checking for this file.
10 On each of the other two lines where error glyphs appear, press Alt-Enter and select the library
declaration that appears.
The greeting.xhtml file contains several pieces of the firstcup application detailed
previously. It uses the localized strings contained in WebMessages.properties and
WebMessages_es.properties. It uses the DukesBDay managed bean to 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.
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 form below. The <fc:inputDate id="userBirthday"
date="#{DukesBDay.yourBD}" /> tag has the required date attribute, and it stores the value in
the yourBD property in the DukesBDay managed bean by 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 in English locales:
The <h:commandButton> tag creates a Submit button and 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 navigation rules for forms in
Facelets pages.
If the form submission is 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 an error with the
input of the inputDate component, a warning message is displayed.
The response.xhtml file displays the age difference between the user and Duke and the average
age difference of all users so far. Different strings are displayed based on whether the user is the
same age, younger, or older than Duke. The text can be displayed or not based on the conditions
specified by the rendered attribute of the <h:outputText> tag. The conditions used in the
rendered attribute are EL language alternatives to the Java programming language conditional
operators to allow XML parsing of the XHTML file.
EQUALS == ==
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:
The form also contains a <h:commandButton> tag that creates a back button that will direct the
user back to the greeting.xhtml page, as specified in the action attribute.
1 Select Web Pages under the firstcup project in the Projects tab.
4 In the File Types pane, select JSF Page, then click Next.
6 If an error glyph appears on the <html> tag, click the error glyph and select Disable HTML
error checking for this file.
7 Repeat the previous steps to create a new Facelets file named response.
1 In the firstcup project, expand the Configuration Files node, then double-click web.xml.
2 Click Pages.
3 Click Browse under Welcome Files, expand Web Pages, select greeting.xhtml, and click Select
File.
4 Edit the Welcome Files text field so that the field looks like this:
faces/greeting.xhtml
1 In the firstcup project, in greeting.xhtml, replace the text between the <h:body> and
</h:body> tags with the following:
<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>
1 In the firstcup project, in response.xhtml, replace the text between the <h:body> and
</h:body> tags with the following:
<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>
3 Type your birth date in the Your birthday text field. Make sure you use the date pattern specified
on the page: MM/dd/yyyy.
4 Click Submit.
5 After the response.xhtml page is displayed, click Back to return to the greeting.xhtml page.
6 Type a different birthday in the text field and click Submit again to see how the average age of
First Cup users changes.
Next Steps
4
This chapter points the user at additional resources for learning more about enterprise
application architecture, the Java EE platform, and Oracle GlassFish Server.
Java EE Servers
Java EE servers are application servers that implement the Java EE platform technologies.
49
Java EE Servers
GlassFish
The GlassFish (https://glassfish.dev.java.net) project is the open-source basis for
GlassFish Server.