[英]JSF/JPA value binding expression not setting entity bean's property
我正在学习JSF / EJB,但遇到了问题。
我正在尝试编写一个从用户那里获取一个字符串并将该字符串存储到数据库的代码。
这是我的代码:实体bean:
@Entity
public class TestTable implements Serializable {
private static final long serialVersionUID = 1L;
public TestTable() {
super();
}
@Id
@GeneratedValue
private int firstcolumn;
private String secondcolumn;
private String testphrase = "test phrase";
public String getTestphrase() {
return testphrase;
}
public void setTestphrase(String testphrase) {
this.testphrase = testphrase;
}
public int getFirstcolumn() {
return firstcolumn;
}
public void setFirstcolumn(int firstcolumn) {
this.firstcolumn = firstcolumn;
}
public String getSecondcolumn() {
return secondcolumn;
}
public void setSecondcolumn(String secondcolumn) {
this.secondcolumn = secondcolumn;
}
}
控制器bean:
@Named
public class TestController implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
DataAccess dacc;
@Inject
TestTable testTable;
public TestController()
{
}
public TestTable getTestTable() {
return testTable;
}
public void setTestTable(TestTable testTable) {
this.testTable = testTable;
}
public void test()
{
System.out.println("string secondcolumn= "+ testTable.getSecondcolumn());
dacc.addtodb(testTable);
}
}
JSF中的值绑定表达式未设置secondcolumn。
现在,JSF:
<h:outputText value="Second column:">
</h:outputText>
<h:inputText label="Second column" value="#{testController.testTable.secondcolumn}">
</h:inputText>
<h:outputText value="#{testController.testTable.getTestphrase()}">
</h:outputText>
<h:commandButton action="#{testController.test}" value="Save">
</h:commandButton>
我检查了数据库,并添加了行。 列SECONDCOLUMN中的条目为NULL。
TESTPHRASE中的条目是“测试短语”。 我没有收到任何错误消息,我已经尽力解决了问题,但现在我陷入了困境。 欢迎任何反馈。
您的问题是您要注入实体类。 最好的办法是使用new
关键字手动将其初始化,从数据库中检索实体,等等。一种方法是在CDI bean中使用@PostConstruct
方法:
@Named
//here you should define the scope of your bean
//probably @RequestScoped
//if you're working with JSF 2.2 there's already a @ViewScoped
public class TestController implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
DataAccess dacc;
//this musn't be injected since it's not a business class but an entity class
//@Inject
TestTable testTable;
public TestController() {
}
@PostConstruct
public void init() {
//basic initialization
testTable = new TestTable();
}
//rest of your code...
}
通过此更改,JSF将能够将<h:form>
的值设置为有界字段。 注意,JSF代码只会根据EL中定义的内容调用必要的getter和setter,而不会创建有界字段的新实例。 生成视图时调用getter,将表单提交给服务器时调用setter。
更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.