1

我正在学习 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;
}



}
  • 表有三列,第一列是主键,第二列存储用户输入的字符串,第三列存储“测试短语”。

控制器豆:

@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);


}

}
  • 我使用 System.out.println("string secondcolumn="+ testTable.getSecondcolumn()); 在方法 test() 中检查数据,然后再将其写入数据库。我的问题是,它始终为空。控制台输出: INFO :string secondcolumn= null 。

secondcolumn 不是由 JSF 中的值绑定表达式设置的。

现在,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 中的条目是“测试短语”。我没有收到任何错误消息,我已尽我所能解决问题,现在我被卡住了。欢迎任何反馈。

4

1 回答 1

2

您的问题是您正在注入一个实体类。最好的方法是使用关键字手动初始化它new,从数据库中检索实体等。一种方法是使用@PostConstructCDI bean 中的方法:

@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。

更多信息:

于 2013-09-09T14:49:28.367 回答