在jsf2中创建动态输入

时间:2013-05-18 11:07:05

标签: jsf-2 richfaces

我想在数据表中的jsf2中创建动态文本框,其中包含基于单击添加行按钮的文本框。我是jsf编程的新手。可以告诉我一个动态生成的基本例子。我已阅读ui:repeatc:foreach,但我需要一些实际的例子。

1 个答案:

答案 0 :(得分:1)

对于您的样本,

xhtml代码:

<?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>
</h:head>
<h:body>
    <h:form  id="form1">
        <h:commandButton value="Add new Row" actionListener="#{myBean.addNewEmployee}"/>
        <h:dataTable value="#{myBean.employeeList}"  var="emp">
            <h:column>
                <f:facet name="header">
                    Employee Id
                </f:facet>
                #{emp.empId}
            </h:column>
            <h:column>
                <h:inputText value="#{emp.empName}"/>
            </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>

jsf manged bean

@ManagedBean
@ViewScoped
public class MyBean implements Serializable {

List<Employee> employeeList;

public List<Employee> getEmployeeList() {
    return employeeList;
}

public void setEmployeeList(List<Employee> employeeList) {
    this.employeeList = employeeList;
}

public void addNewEmployee(ActionEvent event) {
    employeeList.add(new Employee(employeeList.size(), null));
}

@PostConstruct
public void init() {
    employeeList = new ArrayList<Employee>();
    employeeList.add(new Employee(1, "Emp1"));
    employeeList.add(new Employee(2, "Emp2"));
}

public MyBean() {
}
}

员工类(您可以使用您的实体类)

public class Employee {

Integer empId;
String empName;

public Integer getEmpId() {
    return empId;
}

public void setEmpId(Integer empId) {
    this.empId = empId;
}

public String getEmpName() {
    return empName;
}

public void setEmpName(String empName) {
    this.empName = empName;
}

public Employee(Integer empId, String empName) {
    this.empId = empId;
    this.empName = empName;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Employee other = (Employee) obj;
    if (this.empId != other.empId && (this.empId == null || !this.empId.equals(other.empId))) {
        return false;
    }
    return true;
}

@Override
public int hashCode() {
    int hash = 5;
    hash = 41 * hash + (this.empId != null ? this.empId.hashCode() : 0);
    return hash;
}
 }

您可以直接使用上面的代码。而且我建议使用PrimeFaces组件进行高级操作