我有一个简单的数据对象:汽车。我在 JSF 数据表中显示 Car 对象的属性。如果我使用 inputText 标签显示属性,我可以在托管 bean 中获取修改后的值。但是我只想要一个可编辑的单行。因此,在单独的列中放置了一个编辑按钮,并为 Car 的每个属性放置了 inputText 和 outputText。编辑按钮只是切换 inputText 和 outputText 的呈现。另外,我在单独的列中放置了一个更新按钮,用于保存更新的值。但是,在单击更新按钮时,我仍然得到旧值而不是修改后的值。这是完整的代码:
public class Car {
int id;
String brand;
String color;
public Car(int id, String brand, String color) {
this.id = id;
this.brand = brand;
this.color = color;
}
//getters and setters of id, brand, color
}
这是托管bean:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIData;
@ManagedBean(name = "CarTree")
@RequestScoped
public class CarTree {
int editableRowId;
List<Car> carList;
private UIData myTable;
public CarTree() {
carList = new ArrayList<Car>();
carList.add(new Car(1, "jaguar", "grey"));
carList.add(new Car(2, "ferari", "red"));
carList.add(new Car(3, "camri", "steel"));
}
public String update() {
System.out.println("updating...");
//below statments print old values, was expecting modified values
System.out.println("new car brand is:" + ((Car) myTable.getRowData()).brand);
System.out.println("new car color is:" + ((Car) myTable.getRowData()).color);
//how to get modified row values in this method??
return null;
}
public int getEditableRowId() {
return editableRowId;
}
public void setEditableRowId(int editableRowId) {
this.editableRowId = editableRowId;
}
public UIData getMyTable() {
return myTable;
}
public void setMyTable(UIData myTable) {
this.myTable = myTable;
}
public List<Car> getCars() {
return carList;
}
public void setCars(List<Car> carList) {
this.carList = carList;
}
}
这是 JSF 2 页面:
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="carForm" prependId="false">
<h:dataTable id="dt" binding="#{CarTree.myTable}" value="#{CarTree.cars}" var="car" >
<h:column>
<h:outputText value="#{car.id}" />
</h:column>
<h:column>
<h:outputText value="#{car.brand}" rendered="#{CarTree.editableRowId != car.id}"/>
<h:inputText value="#{car.brand}" rendered="#{CarTree.editableRowId == car.id}"/>
</h:column>
<h:column>
<h:outputText value="#{car.color}" rendered="#{CarTree.editableRowId != car.id}"/>
<h:inputText value="#{car.color}" rendered="#{CarTree.editableRowId == car.id}"/>
</h:column>
<h:column>
<h:commandButton value="edit">
<f:setPropertyActionListener target="#{CarTree.editableRowId}" value="#{car.id}" />
</h:commandButton>
</h:column>
<h:column>
<h:commandButton value="update" action="#{CarTree.update}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
但是,如果我只保留 inputText 标签并删除呈现的属性,我会在更新方法中获得修改后的值。如何获取单行编辑的修改值?