在 JSF 2.0 中访问 Bean 属性



我有以下模型代码,我应该使用它。

    public class Client extends User {
    private String userName;
    public Client(String firstName, String lastName, String userName){
        super(firstName, lastName);
        this.userName = userName;
    }
    //getters and setters
}
public abstract class User {
    String firstName;
    String lastName;
   //getters and setters
}

现在我创建了以下 bean:

@ManagedBean(name = "client")
@SessionScoped
public class ClientBean implements Serializable {
    private final long serialVersionUID = 1L; 
    private Client client;
    public Client getClient(){
        return client;
    }
    public void setClient(Client client){
        this.client = client;
    }

}

现在我想在 xhtml 页面中使用此 bean 设置客户端的名字:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <head>
        <title>Register as a client</title>
    </head>
    <body>
        <h:form>
            First Name:<h:inputText value="#{???}"></h:inputText>
            <br/>                  
            <h:commandButton value="Register" action="registered?faces-redirect=true"/>
        </h:form>
    </body>
</html> 

现在我的问题是:如何访问客户的名字?我是否应该创建一个代表用户的新 Bean 并在 ClientBean 中扩展它?(如果是这样,拥有模型代码有什么用?我会到处都有双重代码吗?或者有没有其他更简单的方法在 JSF 2.0 中实现这一点?

您将需要以下内容才能使页面正确显示姓氏。

-- 类用户必须有一个构造函数,如下所示,以及名字和姓氏的 getter 和 setter。

  public User (String firstName, String lastName)

-- 客户端类中用户名的公共获取者和设置方法。

-- 在 ClientBean 类中,我建议你将名称更改为 clientBean。此外,将 getter 和 setter 方法更改为公共而不是私有。如果需要在屏幕上显示客户端对象,则需要创建一个 client 类型的对象并将该对象初始化为某个值。在提供的代码中,您不会创建对象或为任何名称属性提供任何值。

-- 在 JSF 页面中,可以使用 "#{clientBean.client.firstName}" 访问这些值

公开 getter 和 setter

 public Client getClient(){
        return client;
    }
    public void setClient(Client client){
        this.client = client;
    }

如果您的Client null,只需实例化它。

private Client client = new Client();
例如

,如果您想将值持久化到数据库中,或者执行其他一些神奇的操作,例如调用 Web 服务,则可以使用托管 Bean 和 pojo 采用这种方法。

要访问您写的名字#{client.client.firstName} 确实,它看起来有点棒,所以我建议给托管豆起另一个名字。

您可以在托管 Bean 中创建 pojo 的实例:

public class ClientBean implements Serializable {
    private Client client = new Client();
    ...
}

您还可以直接在托管 Bean 中包含名字和姓氏,如果您在保存值的某些操作中创建 pojo,这将很有意义。

JSF 不会将您压在紧身胸衣中,相反,您可以选择适合您的方式。

最新更新