【发布时间】:2016-01-12 03:11:54
【问题描述】:
我有简单的 BMI 类,并尝试使用 JSF 接收输入并显示 BMI 类的结果。但是单击提交按钮后,我的 xhtml 页面没有返回任何内容。 我的 BMI 课程:
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 文件:
<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}"/>
控制器类:
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));
}
}
【问题讨论】:
-
你为什么使用
@SessionScoped?在你的情况下它必须是@ViewScoped -
您使用哪些书籍/教程/资源来学习 JSF?它没有以正确的方式完成。从这里开始:stackoverflow.com/tags/jsf/info
-
感谢您的评论。我正在尝试自己学习 JSF,这是我第一次创建托管 bean 类。我刚刚在这里查看了教程:mkyong.com/jsf2/jsf-2-textbox-example
标签: jsf managed-bean