What do we have in this session 3?
The Facelets pages that you create in the next section will need to access the number that the user types in, and the generated response. To facilitate this, add userNumber
and response
properties to the class.
Start by declaring an Integer named userNumber (in bold).
@ManagedBean(name="UserNumberBean")
@SessionScoped
public class UserNumberBean implements Serializable {
Integer randomInt;
Integer userNumber;
...
...
|
Select userNumber, right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac). Choose Getter and Setter.
|
Select the userNumber : Integer option. Click Generate. Note that the getUserNumber() and setUserNumber(Integer userNumber) methods are added to the class.
The following is the screenshot for the generated Setter and Getter methods.
-----------------------------------------------------------------------------------------------------------
Create a response property. Declare a String named response (in bold).
...
...
*/
@ManagedBean(name = "UserNumberBean")
@SessionScoped
public class UserNumberBean implements Serializable {
Integer randomInt;
Integer userNumber;
String response;
...
...
The following is the screenshot.
Create a getter method for response. (This application will not require a setter.) You could use the IDE's generate code pop-up as shown in the previous step to generate template code.
For purposes of this tutorial however, just paste the below method into the class.
public String getResponse() {
if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0)) {
//invalidate user session
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
session.invalidate();
return "Yay! You got it!";
} else {
return "<p>Sorry, " + userNumber + " isn't it.</p>"
+ "<p>Guess again...</p>";
}
}
The following is the screenshot for the added source code.
-----------------------------------------------------------------------
The above method performs two functions:
1. It tests whether the user-entered number (userNumber) equals the random number generated for the session (randomInt) and returns a String response accordingly.
2. It invalidates the user session if the user guesses the right number (i.e., if userNumber equals randomInt). This is necessary so that a new number is generated should the user want to play again.
Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac). Import statements are automatically created for:
You can press Ctrl-Space on items in the editor to invoke code-completion suggestions and documentation support. Press Ctrl-Space on FacesContext to view the class description from the Javadoc.
Click the web browser ( ) icon in the documentation window to open the Javadoc in an external web browser.