jsf - 如何在托管bean中获取inputText值?

时间:2015-08-02 09:46:33

标签: jsf jsf-2

我有一个inputText我想从中检索值,但看起来它没有在我的bean类中调用setter方法。
这是我的豆类:

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employees")
public class Employee implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    public Employee() {}

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

我正在尝试在ManagedBean类中获取firstName字符串,但它返回null
这是我的控制器类:

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.myapp.model.Employee;

@ManagedBean(name = "controller")
@SessionScoped
public class EmployeeController {

    private Employee employee;  

    @PostConstruct
    public void init()
    {
        employee = new Employee();
    }

    public Employee getEmployee()
    {
        return employee;
    }

    public void showInfo()
    {
        System.out.println("first name: " + employee.getFirstName());
    }

}

这是我的.xhtml文件

<html xmlns="http://www.w3.org/1999/xhtml"  
      xmlns:h="http://java.sun.com/jsf/html"  
      xmlns:f="http://java.sun.com/jsf/core"  
      xmlns:p="http://primefaces.org/ui">  

    <h:head>  

    </h:head>  

    <h:body>  
        <h2>Input:</h2>
        <br/>
        <p:panelGrid columns="2">
            <p:outputLabel value = "First Name:" />
            <p:inputText value = "#{controller.employee.firstName}" />

        </p:panelGrid>
        <br/>
        <h:form>
            <p:commandButton value="Save Edits" action="#{controller.showInfo()}"> </p:commandButton>
        </h:form>
    </h:body>  
</html>  

我做错了什么?

1 个答案:

答案 0 :(得分:0)

<p:inputText>组件必须是正在提交的<h:form>组件的一部分:

<h:form>
    <h2>Input:</h2>
    <br/>
    <p:panelGrid columns="2">
        <p:outputLabel value = "First Name:" />
        <p:inputText value = "#{controller.employee.firstName}" />
    </p:panelGrid>
    <br/>

    <p:commandButton value="Save Edits" action="#{controller.showInfo()}" /> 
</h:form>