Java 在JSF2.0中访问bean属性
我有下面的模型代码,我应该使用它Java 在JSF2.0中访问bean属性,java,jsf,jsf-2,Java,Jsf,Jsf 2,我有下面的模型代码,我应该使用它 public class Client extends User { private String userName; public Client(String firstName, String lastName, String userName){ super(firstName, lastName); this.userName = userName; } //getters a
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中扩展它?(如果是这样的话,有模型代码有什么用?我会在任何地方都有双重代码?)或者在JSF2.0中有没有其他更简单的方法来实现这一点?公开getter和setter
public Client getClient(){
return client;
}
public void setClient(Client client){
this.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不会强迫你穿紧身胸衣,相反,你可以选择适合你的方式。你需要以下内容才能在页面上正确显示姓氏 --类用户必须具有如下所示的构造函数,以及firstname和lastname的getter和setter
public User (String firstName, String lastName)
--客户端类中用户名的公共getter和setter方法
--在ClientBean类中,我建议您将名称更改为ClientBean。另外,将getter和setter方法更改为public而不是private。如果需要在屏幕上显示,则需要创建一个client类型的对象,并将client对象初始化为某个值。在提供的代码中,您没有创建对象或为任何名称属性赋予任何值
--在JSF页面中,您可以使用
“#{clientBean.client.firstName}”
访问这些值。您是否尝试过client.client.firstName?不起作用,client是client的未知属性您需要将getter和setter设置为publicOh垃圾,我为什么要把它们设为私有的:o尝试了这个之后,我在运行它时遇到了以下错误:/registerClient.xhtml@15,79 value=“#{client.client.firstname}”:Target unreable,“null”返回num尝试了这个之后,我在运行它时遇到了以下错误:/registerClient.xhtml@15,79 value=“#{client.client.firstname}”:Target unreable,“null”返回nul(请参见上面的注释)您需要创建pojo的实例,可能在托管bean的构造函数中。@Spindizy我假设他也希望注入ManagedBean。您的方法更好:)在JSF中有很多方法,DI也是一种选择。我没有想到这一点。问题是:客户端没有空构造函数,我们不应该修改模型代码是的,那么您应该使用@PostConstruct方法,并以某种方式将适当的信息输入到支持bean中,以便能够正确初始化客户端,例如通过请求参数。我同意,@PostConstruct是创建bean的另一种方法,稍后用有意义的数据填充值。