@SessionScoped
bean is only created once when the client visit your page for the 1st time. It will then live until the end of the session. In other words, the constructor of your @SessionScoped
bean is only called once. It's not the place to increment your gamesPlayed
.
@ManagedBean
@SessionScoped
public class GameBeans {
private int randomNumber;
private int userGuess;
private int gamesPlayed;
public GameBeans() {
Random number = new Random();
this.randomNumber = number.nextInt(1000);
this.gamesPlayed = 0;
}
public void getWin() {
if (this.userGuess.equals(this.randomNumber))
return "Congratulations! You've Won!";
else return "You Lose!";
}
public void incrementGamesPlayed() {
this.gamePlayed++;
}
// Getters and Setters
}
And this is the play_game.xhtml
:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Guess Numbers Page</title>
</h:head>
<h:body>
<h:form>
<h1>Welcome to Your Game Session</h1>
<p>Number of games played this session: #{gameBeans.gamesPlayed}</p>
<p>Enter your lucky number guess and then click play</p>
<p>Your guess: <h:inputText id="iptxt1" value="#{gameBeans.userGuess}" /></p>
<h:commandButton id="cmdBtn1" value="Play" action="game_result"
actionListener="#{gameBeans.incrementGamesPlayed}" />
</h:form>
</h:body>
</html>