我在同一页中有输入字段和数据表,这样当用户添加新数据时,数据应该添加到数据表中,而不刷新页面。
为了实现这一点,我尝试了以下代码
hospials.xhtml:
<h:form>
<h:outputLabel>Name:</h:outputLabel>
<h:inputText value="#{hospitalsBean.ename}"/>
<h:outputLabel>Address:</h:outputLabel>
<h:inputText value="#{hospitalsBean.hospital.address}"></h:inputText>
<h:commandButton value="A">
<f:ajax event="click" render="table" listener="#{hospitalsBean.command()}"></f:ajax>
</h:commandButton>
</h:form>
<h:dataTable id="table" value="#{hospitalsBean.hospitals}" var="hospital">
<h:column>
<f:facet name="header">Name</f:facet>
#{hospital.name.english}
</h:column>
<h:column>
<f:facet name="header">Address</f:facet>
#{hospital.address}
</h:column>
</h:dataTable>
HospitalsBean.java:
private Hospital hospital = new Hospital();
private ArrayList<Hospital> hospitals = new ArrayList<>();
private Part file; // +getter+setter
public ArrayList<Hospital> getHospitals() {
return MongoCrud.getHospitals();
}
public void setHospitals(ArrayList<Hospital> hospitals) {
this.hospitals = hospitals;
}
public Hospital getHospital() {
return hospital;
}
public void setHospital(Hospital hospital) {
this.hospital = hospital;
}
public void command() throws IOException {
MongoService.insertData("Hospital", Finals.gson.toJson(hospital));
}
但当我将数据插入mongodb时,医院变量没有填充名称和地址
您缺少execute=""
属性,无法在服务器端通过ajax执行组件。
该属性的默认值为@this,这反过来只执行嵌入标签的组件。
所以不是
<f:ajax event="click"
render="table"
listener="#{hospitalsBean.command()}" />
尝试
<f:ajax event="click"
render="table"
execute="@form"
listener="#{hospitalsBean.command()}" />
或提供可编辑值持有者ID:
<h:inputText value="#{hospitalsBean.ename}"
id="ename"/>
<h:inputText value="#{hospitalsBean.hospital.address}"
id="address"/>
<h:commandButton value="A">
<f:ajax event="click"
render="table"
execute="address ename"
listener="#{hospitalsBean.command()}" />
</h:commandButton>