19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Step 2. Create a JSP facelet named GuessNumber as shown in Listing<br />

44.10, GuessNumber.xhtml.<br />

Listing 44.9 GuessNumber.java<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

package jsf2demo;<br />

import javax.faces.bean.ManagedBean;<br />

import javax.faces.bean.ViewScoped;<br />

@ManagedBean<br />

@ViewScoped<br />

public class GuessNumber {<br />

private int number;<br />

private String guessString;<br />

public GuessNumber() {<br />

number = (int)(Math.random() * 100);<br />

}<br />

public String getGuessString() {<br />

return guessString;<br />

}<br />

public void setGuessString(String guessString) {<br />

this.guessString = guessString;<br />

}<br />

public String getResponse() {<br />

if (guessString == null)<br />

return ""; // No user input yet<br />

}<br />

}<br />

int guess = Integer.parseInt(guessString);<br />

if (guess < number)<br />

return "Too low";<br />

else if (guess == number)<br />

return "You got it";<br />

else<br />

return "Too high";<br />

The managed bean uses the @ViewScope annotation (line 5) <strong>to</strong> set up the<br />

view scope for the bean. The view scope is most appropriate for this<br />

project. The bean is alive as long as the view is not changed. The bean<br />

is created when the page is displayed for the first time. A random<br />

number between 0 and 99 is assigned <strong>to</strong> number (line 13) when the bean is<br />

created. This number will not change as long as the bean is alive.<br />

24

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!