[英]Accessing bean properties in JSF 2.0
我有以下应该使用的模型代码。
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中还有其他更简单的方法来实现这一点吗?
该页面需要以下内容才能正确显示姓氏。
-User类必须具有以下构造函数,以及用于firstname和lastname的getter和setter。
public User (String firstName, String lastName)
-Client类中用户名的公共getter和setter方法。
-在ClientBean类中,建议您将名称更改为clientBean。 另外,将getter和setter方法更改为public而不是private。 如果需要在屏幕上显示该对象,则需要创建一个类型为client的对象并将其初始化为某个值。 在提供的代码中,您不会创建对象或为任何名称属性提供任何值。
-在JSF页面中,您可以使用"#{clientBean.client.firstName}"
访问值
公开获取器和设置器
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再加上一个名字。
您可以在托管bean中创建pojo的实例:
public class ClientBean implements Serializable {
private Client client = new Client();
...
}
您还可以在托管bean中直接包含名字和姓氏,以防在某些操作中创建pojo来保存值时这样做。
JSF不会紧身胸衣,而是可以选择适合您的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.