Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Capítulo 39 - JavaServer Faces - Liang-Java-Comp11e, Resumos de Informática

JavaServer Faces

Tipologia: Resumos

2018

Compartilhado em 21/07/2018

dddmmm80-5
dddmmm80-5 🇧🇷

4.8

(4)

13 documentos

1 / 52

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
Objectives
To explain what JSF is (§39.1).
To create a JSF project in NetBeans (§39.2.1).
To create a JSF page (§39.2.2).
To create a JSF managed bean (§39.2.3).
To use JSF expressions in a facelet (§39.2.4).
To use JSF GUI components (§39.3).
To obtain and process input from a form (§39.4).
To develop a calculator using JSF (§39.5).
To track sessions in application, session, view, and request scopes
(§39.6).
To validate input using the JSF validators (§39.7).
To bind database with facelets (§39.8).
To open a new JSF page from the current page (§39.9).
To program using contexts and dependency injection (§39.10).
JavaServer Faces
CHAPTER
39
M39_LIAN0182_11_SE_C39.indd 1 5/26/17 7:21 PM
© 2018 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34

Pré-visualização parcial do texto

Baixe Capítulo 39 - JavaServer Faces - Liang-Java-Comp11e e outras Resumos em PDF para Informática, somente na Docsity!

Objectives

■ ■ To explain what JSF is (§39.1).

■ ■ To create a JSF project in NetBeans (§39.2.1).

■ ■ To create a JSF page (§39.2.2).

■ ■ To create a JSF managed bean (§39.2.3).

■ ■ To use JSF expressions in a facelet (§39.2.4).

■ ■ To use JSF GUI components (§39.3).

■ ■ To obtain and process input from a form (§39.4).

■ ■ To develop a calculator using JSF (§39.5).

■ ■ To track sessions in application, session, view, and request scopes

■ ■ To validate input using the JSF validators (§39.7).

■ ■ To bind database with facelets (§39.8).

■ ■ To open a new JSF page from the current page (§39.9).

■ ■ To program using contexts and dependency injection (§39.10).

JavaServer Faces

CHAPTER

39-2 Chapter 39 JavaServer Faces

39.1 Introduction

JavaServer Faces (JSF) is a new technology for developing server-side Web

applications using Java.

JSF enables you to completely separate Java code from HTML. You can quickly build Web

applications by assembling reusable UI components in a page, connecting these components

to Java programs and wiring client-generated events to server-side event handlers. The applica-

tion developed using JSF is easy to debug and maintain.

Note This chapter introduces JSF 2, the latest standard for JavaServer Faces. You need to know XHTML (eXtensible HyperText Markup Language) and CSS (Cascading Style Sheet) to start this chapter. For information on XHTML and CSS, see Supplements V.A and V.B.

Caution The examples and exercises in this chapter were tested using NetBeans 7.3.1, GlassFish 4, and Java EE 7. You need to use NetBeans 7.3.1 or a higher version with GlassFish 4 and Java EE 7 to develop your JSF projects.

39.2 Getting Started with JSF

NetBeans is an effective tool for developing JSF applications.

We begin with a simple example that illustrates the basics of developing JSF projects using

NetBeans. The example is to display the date and time on the server, as shown in Figure 39.1.

JSF

JSF 2

XHTML

CSS

NetBeans 7.3. GlassFish 4 Java EE 7

Point

Key

Figure 39.1 The application displays the date and time on the server.

Point

Key

39.2.1 Creating a JSF Project

Here are the steps to create the application.

Step 1: Choose File , New Project to display the New Project dialog box. In this box,

choose Java Web in the Categories pane and Web Application in the Projects pane. Click

Next to display the New Web Application dialog box.

In the New Web Application dialog box, enter and select the following fields, as shown

in Figure 39.2a:

Project Name: jsf2demo

Project Location: c:\book

Step 2: Click Next to display the dialog box for choosing servers and settings. Select the

following fields as shown in Figure 39.2b. (Note: You can use any server such as Glass-

Fish 4.x that supports Java EE 6.)

Server: GlassFish 4

Java EE Version: Java EE 7 Web

create a project

choose server and Java EE 7

39-4 Chapter 39 JavaServer Faces

7 <h:head> 8 Facelet Title 9 </h:head> 10 <h:body> 11 Hello from Facelets 12 </h:body> 13

Line 1 is an XML declaration to state that the document conforms to the XML version 1.0 and

uses the UTF-8 encoding. The declaration is optional, but it is a good practice to use it. A docu-

ment without the declaration may be assumed of a different version, which may lead to errors.

If an XML declaration is present, it must be the first item to appear in the document. This is

because an XML processor looks for the first line to obtain information about the document

so that it can be processed correctly.

Line 2 is a comment for documenting the contents in the file. XML comment always begins

with .

Lines 3 and 4 specify the version of XHTML used in the document. This can be used by

the Web browser to validate the syntax of the document.

An XML document consists of elements described by tags. An element is enclosed between a

start tag and an end tag. XML elements are organized in a tree-like hierarchy. Elements may con-

tain subelements, but there is only one root element in an XML document. All the elements must

be enclosed inside the root tag. The root element in XHTML is defined using the html tag (line 5).

Each tag in XML must be used in a pair of the start tag and the end tag. A start tag begins

with < followed by the tag name and ends with >. An end tag is the same as its start tag except

that it begins with </. The start tag and end tag for html are and .

The html element is the root element that contains all other elements in an XHTML page.

The starting tag (lines 5 and 6) may contain one or more xmlns (XML namespace)

attributes to specify the namespace for the elements used in the document. Namespaces are like

Java packages. Java packages are used to organize classes and to avoid naming conflict. XHTML

namespaces are used to organize tags and resolve naming conflict. If an element with the same

name is defined in two namespaces, the fully qualified tag names can be used to differentiate them.

h:head

h:body

XML declaration

XML comment

DOCTYPE

element tag

html tag

Figure 39.4 A default JSF page is created in a new Web project.

39.2 Getting Started with JSF 39-

Each xmlns attribute has a name and a value separated by an equal sign ( = ). The following

declaration (line 5)

xmlns="http://www.w3.org/1999/xhtml"

specifies that any unqualified tag names are defined in the default standard XHTML namespace.

The following declaration (line 6)

xmlns:h="http://xmlns.jcp.org/jsf/html"

allows the tags defined in the JSF tag library to be used in the document. These tags must have

a prefix h.

An html element contains a head and a body. The h:head element (lines 7–9) defines an

HTML title element. The title is usually displayed in the browser window’s title bar.

An h:body element defines the page’s content. In this simple example, it contains a string

to be displayed in the Web browser.

Note The XML tag names are case sensitive, whereas HTML tags are not. So, is differ- ent from in XML. Every start tag in XML must have a matching end tag, whereas some tags in HTML do not need end tags.

You can now display the page in index.xhtml by right-clicking on index.xhtml in the projects

pane and choose Run File. The page is displayed in a browser, as shown in Figure 39.5.

xmlns

h:head

h:body

Figure 39.5 The index.xhtml is displayed in the browser.

Note The JSF page is processed and converted into a regular HTML page for displaying by a browser. The Java software that runs on the server side for producing the HTML page is known as Java server container or simply container. The container is responsible for handling all server-side tasks for Java EE. GlassFish is a Java server container.

39.2.3 Managed JavaBeans for JSF

JSF applications are developed using the Model-View-Controller (MVC) architecture, which

separates the application’s data (contained in the model) from the graphical presentation (the

view). The controller is the JSF framework that is responsible for coordinating interactions

between view and the model.

In JSF, the facelets are the view for presenting data. Data are obtained from Java objects.

Objects are defined using Java classes. In JSF, the objects that are accessed from a facelet are

JavaBeans objects. A JavaBean class is simply a public Java class with a no-arg constructor.

JavaBeans may contain properties. By convention, a property is defined with a getter and a

setter method. If a property only has a getter method, the property is called a read-only prop-

erty. If a property only has a setter method, the property is called a write-only property. A

property does not need to be defined as a data field in the class.

container

JavaBean

39.2 Getting Started with JSF 39-

Figure 39.7 Specify the name, location, and scope for the bean.

Figure 39.8 A JavaBean for JSF was created.

39-8 Chapter 39 JavaServer Faces

Listing 39.2 TimeBean.java 1 package jsf2demo; 2 3 import javax.inject.Named; 4 import javax.enterprise.context.RequestScoped; 5 6 @Named (value = "timeBean") 7 @RequestScoped 8 public class TimeBean { 9 public TimeBean() { 10 } 11 12 public String getTime() { 13 return new java.util.Date().toString(); 14 } 15 }

TimeBean is a JavaBeans with the @Named annotation, which indicates that the JSF framework

will create and manage the TimeBean objects used in the application. You have learned to use

the @Override annotation in Chapter 11. The @Override annotation tells the compiler that

the annotated method is required to override a method in a superclass. The @Named annotation

tells the compiler to generate the code to enable the bean to be used by JSF facelets.

The @RequestScope annotation specifies that the scope of the JavaBeans object is within a

request. You can also use @ViewScope , @SessionScope or @ApplicationScope to specify

the scope for a session or for the entire application.

39.2.4 JSF Expressions

We demonstrate JSF expressions by writing a simple application that displays the current time.

You can display current time by invoking the getTime() method in a TimeBean object using

a JSF expression.

To keep index.xhtml intact, we create a new JSF page named CurrentTime.xhtml as follows:

Step 1. Right-click the jsf2demo node in the project pane to display a context menu and

choose New , JSF Page to display the New JSF File dialog box, as shown in Figure 39.9.

Step 2. Enter CurrentTime in the File Name field, choose Facelets and click Finish to

generate CurrentTime.xhtml, as shown in Figure 39.10.

Step 3. Add a JSF expression to obtain the current time, as shown in Listing 39.3.

Step 4. Right-click on CurrentTime.xhtml in the project to display a context menu and

choose Run File to display the page in a browser as shown in Figure 39.1.

Listing 39.3 CurrentTime.xhtml

1 2 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html"> 6 <h:head> 7 Display Current Time 8 9 </h:head> 10 <h:body> 11 The current time is #{timeBean.time} 12 </h:body> 13

@Named @RequestScoped

time property

@RequestScope

refresh page

JSF expression

39-10 Chapter 39 JavaServer Faces

Line 8 uses a JSF expression #{timeBean.time} to obtain the current time. timeBean is

an object of the TimeBean class. The object name can be changed in the @Named annotation

(line 6 in Listing 39.2) using the following syntax:

@Named(name = "anyObjectName")

By default, the object name is the class name with the first letter in lowercase.

Note that time is a JavaBeans property because the getTime() method is defined in Time-

Beans. The JSF expression can either use the property name or invoke the method to obtain

the current time. So the following two expressions are fine:

#{timeBean.time} #{timeBean.getTime()}

The syntax of a JSF expression is

#{expression}

JSF expressions bind JavaBeans objects with facelets. You will see more use of JSF expres-

sions in the upcoming examples in this chapter.

39.2.1 What is JSF? 39.2.2 How do you create a JSF project in NetBeans? 39.2.3 How do you create a JSF page in a JSF project? 39.2.4 What is a facelet? 39.2.5 What is the file extension name for a facelet? 39.2.6 What is a managed bean? 39.2.7 What is the @Named annotation for? 39.2.8 What is the @RequestScope annotation for?

39.3 JSF GUI Components

JSF provides many elements for displaying GUI components.

Table 39.1 lists some of the commonly used elements. The tags with the h prefix are in the JSF

HTML Tag library. The tags with the f prefix are in the JSF Core Tag library.

Listing 39.4 is an example that uses some of these elements to display a student registration

form, as shown in Figure 39.11.

Listing 39.4 StudentRegistrationForm.xhtml 1 2 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html" 6 xmlns:f="http://xmlns.jcp.org/jsf/core"> 7 <h:head> 8 Student Registration Form 9 </h:head> 10 <h:body> 11 <h:form> 12 13

Student Registration Form 14 <h:graphicImage name="usIcon.gif" library="image"/> 15

Point

Check

Point

Key

jsf core namespace

graphicImage

39.3 JSF GUI Components 39-

JSF Tag Description

h:form inserts an XHTML form into a page.

h:panelGroup similar to a JavaFX FlowPane.

h:panelGrid similar to a JavaFX GridPane.

h:inputText displays a textbox for entering input.

h:outputText (^) displays a textbox for displaying output.

h:inputTextArea (^) displays a textarea for entering input.

h:inputSecret (^) displays a textbox for entering password.

h:outputLabel displays a label.

h:outputLink displays a hypertext link.

h:selectOneMenu displays a combo box for selecting one item.

h:selectOneRadio displays a set of radio button.

h:selectManyCheckbox (^) displays checkboxes.

h:selectOneListbox (^) displays a list for selecting one item.

h:selectManyListbox displays a list for selecting multiple items.

f:selectItem specifies an item in an h:selectOneMenu , h:selectOneRadio , or h:selectManyListbox.

h:message (^) displays a message for validating input.

h:dataTable (^) displays a data table.

h:column specifies a column in a data table.

h:graphicImage displays an image.

tabLe 39.1 JSF GUI Form Elements

Figure 39.11 A student registration form is displayed using JSF elements.

39.3 JSF GUI Components 39-

The tags with prefix f are in the JSF core tag library. Line 6

xmlns:f="http://xmlns.jcp.org/jsf/core">

locates the library for these tags.

The h:graphicImage tag displays an image in the file usIcon.gif (line 14). The file is

located in the /resources/image folder. In JSF 2.0, all resources (image files, audio files, and

CCS files) should be placed under the resources folder under the Web Pages node. You

can create these folders as follows:

Step 1: Right-click the Web Pages node in the project pane to display a context menu

and choose New , Folder to display the New Folder dialog box. (If Folder is not in the

context menu, choose Other to locate it.)

Step 2: Enter resources as the Folder Name and click Finish to create the resources

folder, as shown in Figure 39.12.

Step 3: Right-click the resources node in the project pane to create the image folder

under resources. You can now place usIcon.gif under the image folder.

jsf core xmlns

h:graphicImage

Figure 39.12 The resources folder was created.

JSF provides h:panelGrid and h:panelGroup elements to contain and layout subele-

ments. h:panelGrid places the elements in a grid like the JavaFX GridPane. h:panelGrid

places the elements in a grid with the specified number of columns. Lines 18–25 place six

elements (labels and input texts) that are in an h:panelGrid. The columns attribute specifies

that each row in the grid has 6 columns. The elements are placed into a row from left to right

in the order they appear in the facelet. When a row is full, a new row is created to hold the

elements. We used h:panelGrid in this example. You may replace it with h:panelGroup

to see how the elements would be arranged.

You may use the style attribute with a JSF html tag to specify the CSS style for the ele-

ment and its subelements. The style attribute in line 18 specifies the color green for all ele-

ments in this h:panelGrid element.

The h:outputLabel element is for displaying a label (line 19). The value attribute speci-

fies the label’s text.

The h:inputText element is for displaying a text input box for the user to enter a text

(line 20). The id attribute is useful for other elements or the server program to reference this

element.

The h:selectOneRadio element is for displaying a group of radio buttons (line 30). Each

radio button is defined using an f:selectItem element (lines 31–34).

h:panelGrid

the style attribute

h:outputLabel

h:inputText

h:selectOneRadio

39-14 Chapter 39 JavaServer Faces

The h:selectOneMenu element is for displaying a combo box (line 41). Each item in the

combo box is defined using an f:selectItem element (lines 42 and 43).

The h:selectManyListbox element is for displaying a list for the user to choose multiple

items in a list (line 46). Each item in the list is defined using an f:selectItem element (lines

The h:selectManyCheckbox element is for displaying a group of check boxes (line 56).

Each item in the check box is defined using an f:selectItem element (lines 57–59).

The h:selectTextarea element is for displaying a text area for multiple lines of input

(line 66). The style attribute is used to specify the width and height of the text area (line 67).

The h:commandButton element is for displaying a button (line 71). When the button is

clicked, an action is performed. The default action is to request the same page from the server.

The next section shows how to process the form.

39.3.1 What is the name space for JSF tags with prefix h and prefix f? 39.3.2 Describe the use of the following tags?

1 h:form , h:panelGroup , h:panelGrid , h:inputText , h:outputText ,

2 h:inputTextArea , h:inputSecret , h:outputLabel , h:outputLink , 3 h:selectOneMenu , h:selectOneRadio , h:selectBooleanCheckbox , 4 h:selectOneListbox , h:selectManyListbox , h:selectItem , 5 h:message , h:dataTable , h:columm , h:graphicImage

39.4 Processing the Form

Processing forms is a common task for Web programming. JSF provides tools for pro-

cessing forms.

The preceding section introduced how to display a form using common JSF elements. This

section shows how to obtain and process the input.

To obtain input from the form, simply bind each input element with a property in a man-

aged bean. We now define a managed bean named registration as shown in Listing 39.5.

Listing 39.5 RegistrationJSFBean.java 1 package jsf2demo; 2 3 import javax.enterprise.context.RequestScoped; 4 import javax.inject.Named; 5 6 @Named(value = "registration") 7 @RequestScoped 8 public class RegistrationJSFBean { 9 private String lastName; 10 private String firstName; 11 private String mi; 12 private String gender; 13 private String major; 14 private String[] minor; 15 private String[] hobby; 16 private String remarks; 17 18 public RegistrationJSFBean() { 19 } 20 21 public String getLastName() { 22 return lastName; 23 }

h:selectOneMenu

h:selectManyListbox

h:selectManyCheckbox

h:selectTextarea

h:commandButton

Point

Check

Point

Key

managed bean request scope property lastName

39-16 Chapter 39 JavaServer Faces

85 public String getResponse() { 86 if (lastName == null ) 87 return "" ; // Request has not been made 88 else { 89 String allMinor = "" ; 90 for (String s: minor) { 91 allMinor += s + " " ; 92 } 93 94 String allHobby = "" ; 95 for (String s: hobby) { 96 allHobby += s + " " ; 97 } 98 99 return "<p style="color:red">You entered
"
+ 100 "Last Name: " + lastName + "
"
+ 101 "First Name: " + firstName + "
"
+ 102 "MI: " + mi + "
"
+ 103 "Gender: " + gender + "
"
+ 104 "Major: " + major + "
"
+ 105 "Minor: " + allMinor + "
"
+ 106 "Hobby: " + allHobby + "
"
+ 107 "Remarks: " + remarks + "

" ; 108 } 109 } 110 }

The RegistrationJSFBean class is a managed bean that defines the properties lastName ,

firstName , mi , gender , major , minor , and remarks , which will be bound to the elements

in the JSF registration form.

The registration form can now be revised as shown in Listing 39.6. Figure 39.13 shows that

new JSF page displays the user input upon clicking the Register button.

Listing 39.6 ProcessStudentRegistrationForm.xhtml

1 2 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html" 6 xmlns:f="http://xmlns.jcp.org/jsf/core"> 7 <h:head> 8 Student Registration Form 9 </h:head> 10 <h:body> 11 <h:form> 12 13

Student Registration Form 14 <h:graphicImage name="usIcon.gif" library="image"/> 15

16 17 18 <h:panelGrid columns="6" style="color:green"> 19 <h:outputLabel value="Last Name"/> 20 <h:inputText id="lastNameInputText" 21 value="#{registration.lastName}"/> 22 <h:outputLabel value="First Name" /> 23 <h:inputText id="firstNameInputText" 24 value="#{registration.firstName}"/>

getResponse()

bean properties

jsf core namespace

bind lastName

bind firstName

39.4 Processing the Form 39-

25 <h:outputLabel value="MI" /> 26 <h:inputText id="miInputText" size="1" 27 value="#{registration.mi}"/> 28 </h:panelGrid> 29 30 31 <h:panelGrid columns="2"> 32 <h:outputLabel>Gender </h:outputLabel> 33 <h:selectOneRadio id="genderSelectOneRadio" 34 value="#{registration.gender}"> 35 <f:selectItem itemValue="Male" 36 itemLabel="Male"/> 37 <f:selectItem itemValue="Female" 38 itemLabel="Female"/> 39 </h:selectOneRadio> 40 </h:panelGrid> 41 42 43 <h:panelGrid columns="4"> 44 <h:outputLabel value="Major "/> 45 <h:selectOneMenu id="majorSelectOneMenu" 46 value="#{registration.major}"> 47 <f:selectItem itemValue="Computer Science"/> 48 <f:selectItem itemValue="Mathematics"/> 49 </h:selectOneMenu> 50 <h:outputLabel value="Minor "/> 51 <h:selectManyListbox id="minorSelectManyListbox" 52 value="#{registration.minor}"> 53 <f:selectItem itemValue="Computer Science"/> 54 <f:selectItem itemValue="Mathematics"/> 55 <f:selectItem itemValue="English"/> 56 </h:selectManyListbox> 57 </h:panelGrid> 58 59 60 <h:panelGrid columns="4"> 61 <h:outputLabel value="Hobby: "/> 62 <h:selectManyCheckbox id="hobbySelectManyCheckbox" 63 value="#{registration.hobby}"> 64 <f:selectItem itemValue="Tennis"/> 65 <f:selectItem itemValue="Golf"/> 66 <f:selectItem itemValue="Ping Pong"/> 67 </h:selectManyCheckbox> 68 </h:panelGrid> 69 70 71 <h:panelGrid columns="1"> 72 <h:outputLabel>Remarks:</h:outputLabel> 73 <h:inputTextarea id="remarksInputTextarea" 74 style="width:400px; height:50px;" 75 value="#{registration.remarks}"/> 76 </h:panelGrid> 77 78 79 <h:commandButton value="Register" /> 80
81 <h:outputText escape="false" style="color:red" 82 value="#{registration.response}" /> 83 </h:form> 84 </h:body> 85

bind mi

bind gender

bind major

bind minor

bind hobby

bind remarks

bind response

39.5 Case Study: Calculator 39-

The h:outputText element’s escape attribute is set to false (line 81) to enable the

contents to be displayed in HTML. By default, the escape attribute is true , which indicates

the contents are considered regular text.

39.4.1 In the h:outputText tag, what is the escape attribute for?

39.4.2 Does every GUI component tag in JSF have the style attribute?

39.5 Case Study: Calculator

This section gives a case study on using GUI elements and processing forms.

This section uses JSF to develop a calculator to perform addition, subtraction, multiplication,

and division, as shown in Figure 39.14.

escape attribute

Point

Check

Point

Key

Figure 39.14 This JSF application enables you to perform addition, subtraction,

multiplication, and division.

Here are the steps to develop this project:

Step 1. Create a new managed bean named calculator with the request scope as

shown in Listing 39.7, CalculatorJSFBean.java.

Step 2. Create a JSF facelet in Listing 39.8, Calculator.xhtml.

Listing 39.7 CalculatorJSFBean.java

1 package jsf2demo; 2 3 import javax.inject.Named; 4 import javax.enterprise.context.RequestScoped; 5 6 @Named(value = "calculator" ) 7 @RequestScoped 8 public class CalculatorJSFBean { 9 private Double number1; 10 private Double number2; 11 private Double result; 12 13 public CalculatorJSFBean() { 14 } 15 16 public Double getNumber1() { 17 return number1; 18 } 19 20 public Double getNumber2() { 21 return number2; 22 } 23

create managed bean

create JSF facelet

property number property number property result

39-20 Chapter 39 JavaServer Faces

24 public Double getResult() { 25 return result; 26 } 27 28 public void setNumber1(Double number1) { 29 this .number1 = number1; 30 } 31 32 public void setNumber2(Double number2) { 33 this .number2 = number2; 34 } 35 36 public void setResult(Double result) { 37 this .result = result; 38 } 39 40 public void add() { 41 result = number1 + number2; 42 } 43 44 public void subtract() { 45 result = number1 - number2; 46 } 47 48 public void divide() { 49 result = number1 / number2; 50 } 51 52 public void multiply() { 53 result = number1 * number2; 54 } 55 }

The managed bean has three properties number1 , number2 , and result (lines 9–38). The

methods add() , subtract() , divide() , and multiply() add, subtract, multiply, and

divide number1 with number2 and assigns the result to result (lines 40–54).

Listing 39.8 Calculator.xhtml 1 2 4 <html xmlns="http://www.w3.org/1999/xhtml" 5 xmlns:h="http://xmlns.jcp.org/jsf/html"> 6 <h:head> 7 Calculator 8 </h:head> 9 <h:body> 10 <h:form> 11 <h:panelGrid columns="6"> 12 <h:outputLabel value="Number 1"/> 13 <h:inputText id="number1InputText" size ="4" 14 style="text-align: right" 15 value="#{calculator.number1}"/> 16 <h:outputLabel value="Number 2" /> 17 <h:inputText id="number2InputText" size ="4" 18 style="text-align: right" 19 value="#{calculator.number2}"/> 20 <h:outputLabel value="Result" /> 21 <h:inputText id="resultInputText" size ="4"

add

subtract

divide

multiply

right align bind text input