Search code examples
jsfmanaged-bean

xhtml not returning anything after button submit in JSF


I have the simple BMIclass and trying to use JSF to receive input and display the result of BMI class. But after click submit button, my xhtml page doesn't return anything. My BMI class:

   public class BMI {
   private static int weight;
   private static int height;
   private static double bmi;
   private  static String bmiCategory;

public static int getWeight() {
    return weight;
}
public void setWeight(int weight) {
    this.weight = weight;
}
public static int getHeight() {
    return height;
}
public void setHeight(int height) {
    this.height = height;
}



public BMI(int weight, int height) {
    super();
    this.weight = weight;
    this.height = height;
    bmi();
    bmiCategory();
}
public BMI() {
    super();
    // TODO Auto-generated constructor stub
}

public  double bmi () {

    double bmi;
    bmi = (double)(703 * weight) / (height * height );  
    return bmi;
}

public  String bmiCategory () {

    if (bmi() < 18.5) {
        bmiCategory = "Under weight";
    } else if (bmi() <= 24.9) {
        bmiCategory = "Normal";
    } else if (bmi() <= 29.9) {
        bmiCategory = "Over weight";
    } else {
        bmiCategory = "Obese";
    }
    return bmiCategory;
}

}

XHTML file:

    <h:body>
<h:form>
<p:panel id="panel" header="BMI Calculator" style="margin-bottom:10px;">
    <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />
    <h:panelGrid columns="2" cellpadding="5">
        <h:outputLabel for="weight" value="Weight(in lbs):" />
        <p:inputText id = "weight" value="#{bmiController.bmiBean.weight}" required="true" />

        <h:outputLabel for="height" value="Height(in inches):" />
        <p:inputText id = "height" value="#{bmiController.bmiBean.height}" required="true" />required="true" />


    </h:panelGrid>
</p:panel>

   <p:commandButton value="Calculator" update="panel" actionListener="#{bmiController.calculate}"/>

Controller Class:

  import javax.faces.application.FacesMessage;



 @Named
 @ViewScoped

  public class BmiController implements Serializable {

/**
 * 
 */
  private static final long serialVersionUID = 1L;


  BMI bmiBean = new BMI(); 

public BMI getBmiBean() {
    return bmiBean;
}

public void setBmi (BMI bmiBean) {
    this.bmiBean = bmiBean;
}

public void calculate() {


    String message1 = ("%s Your BMI is" + bmiBean.bmi() + "%s and you are" + bmiBean.bmi());            
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO,"1234", message1));


}

}


Solution

  • Change your #{BmiController.weight} into #{bmiController.weight} in xhtml page that will work.

    Replace all BmiController into bmiController in your XHTML page.