Java Reference
In-Depth Information
Three text input components along with their labels are placed in the grid panel (lines 11-24).
Four button components are placed in the grid panel (lines 26-35).
The bean property
number1
is bound to the text input for Number 1 (line 15). The CSS
style
text-align: right
(line 14) specifies that the text is right-aligned in the input box.
The
action
attribute for the
Add
button is set to the
add
method in the calculator bean
(line 28). When the
Add
button is clicked, the
add
method in the bean is invoked to add
number1
with
number2
and assign the result to
result
. Since the
result
property is bound
to the Result input text (line 23), the new result is now displayed in the text input field.
You can create a managed bean at the application scope, session scope, view scope,
or request scope.
Key
Point
JSF supports session tracking using JavaBeans at the application scope, session scope, view
scope, and request scope. The
scope
is the lifetime of a bean. A
request
-scoped bean is alive
in a single HTTP request. After the request is processed, the bean is no longer alive. A
view
-
scoped bean lives as long as you are in the same JSF page. A
session
-scoped bean is alive
for the entire Web session between a client and the server. An
application
-scoped bean lives
as long as the Web application runs. In essence, a request-scoped bean is created once for a
request; a view-scoped bean is created once for the view; a session-scoped bean is created
once for the entire session; and an application-scoped bean is created once for the entire
application.
Consider the following example that prompts the user to guess a number. When the page starts,
the program randomly generates a number between
0
and
99
. This number is stored in a bean.
When the user enters a guess, the program checks the guess with the random number in the bean
and tells the user whether the guess is too high, too low, or just right, as shown in FigureĀ 33.15.
Here are the steps to develop this project:
scope
request scope
view scope
session scope
application scope
Step 1. Create a new managed bean named
guessNumber
with the view scope as shown
in Listing 33.9, GuessNumberJSFBean.java.
create managed bean
Step 2. Create a JSF facelet in Listing 33.10, GuessNumber.xhtml.
create JSF facelet
L
ISTING
33.9
GuessNumberJSFBean.java
1
package
jsf2demo;
2
3
import
javax.inject.Named;
4
import
javax.faces.view.ViewScoped;
5
6 @Named(value =
"guessNumber"
)
7 @ViewScoped
8
public class
GuessNumberJSFBean {
9
view scope
private int
number;
random number
guess by user
10
private
String guessString;
11
12
public
GuessNumberJSFBean() {
13 number = (
int
)(Math.random() *
100
);
14 }
15
16
create random number
public
String getGuessString() {
getter method
17
return
guessString;
18 }
19
20
public void
setGuessString(String guessString) {
setter method
21
this
.guessString = guessString;
22 }
Search WWH ::
Custom Search