1

I'm trying to pass form text from my XHTML file into my java bean class into a variable called userNumber but cannot work out how to pass the user inputted number into the java bean class variable.

Here is the code for the XHTML file:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Numbers Page</title>
    </h:head>
    <h:body>
        <h1></h1>
        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <p>Your guess: <h:form> <input type="text" name="numberGuess">
        <p></p>
        <h:commandButton value="Play" action="game_result"/>
        </input></h:form></p>
    </h:body>
</html>

Here is the code for the java bean class:

import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class GameBean
{    
    public String getNumber()
    {
        String userNumber = request.getparameter("numberGuess");
        return userNumber;
    }

    public int getLuckyNumber()
    {
        Random number = new Random();
        return number.nextInt(1000000)+1; 
    }    
}

Please help! Thanks!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Adnan
  • 19
  • 1
  • 5

1 Answers1

0

Adnan I think you are learning jsf and have a misunderstanding of how jsf works and the model binding if offers compared against servlets and jsp that is more focused in request and response http objects abstraction, in fact in jsf you could get values from the request but is not correct way to do. For you case you could bind the value in this way

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Numbers Page</title>
    </h:head>
    <h:body>            
        <p>Your guess: 
           <h:form> 
                <h:inputText value="#{game.number}"/>
                <h:commandButton value="Play" action="game_result"/>
           </h:form>
        </p>
    </h:body>
</html>

And your managed bean must be

@ManagedBean(name="game")
@RequestScoped
public class GameBean
{
   private String number;
   public String getNumber() {
      return this.number;
   }
   public void setNumber(String number) {
      this.number = number;
   }    
}

Note that I set the name of the bean as game @ManagedBean(name="game") and it's bind to the input <h:inputText value="#{game.number}"/> in the property number of the bean game, in this way jsf set the value in the property name the value of the input each time it send the form to the server.

You could also get the request value in this way

FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderValuesMap().get("numberGuess");
Cesar Loachamin
  • 2,740
  • 4
  • 25
  • 33
  • I've done what you mentioned but I don't get any output on my results xhtml page. Please help! – Adnan Mar 23 '15 at 18:02