我非常清楚
Any scoped managed bean method annotated with @PostConstruct will be called
after the managed bean is instantiated, but before the bean is placed in scope.
考虑
<h:inputText binding="#{bean.input}" >
</h:inputText>
托管bean是
public class Bean {
private HtmlInputText input;
public PreInitializeBean(){
input = new HtmlInputText();
input.setMaxlength(15);
input.setStyle("background: pink;");
input.setValue(fetchValueFromDatabase());
}
private Object fetchValueFromDatabase() {
String resultValue = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "system");
System.out.println("Connection Object: "+con);
// retieving data from RESULT table
PreparedStatement ps = con
.prepareStatement("select * from RESULT",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.print("<br>" + rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3) + " " + rs.getString(4));
resultValue = rs.getString(2);
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultValue;
}
public HtmlInputText getInput() {
return input;
}
public void setInput(HtmlInputText input) {
this.input = input;
}
}
当我在Contructor中执行初始化时,我在inputtext字段中什么都没有,但是我得到了预期的(inputtext框中的值),如果我在做什么,我把它放在一个标有@PostContruct的方法中。登记/> 将构造函数方法替换为:
@PostConstruct
public void init() {
input = new HtmlInputText();
input.setMaxlength(15);
input.setStyle("background: pink;");
input.setValue(fetchValueFromDatabase());
}
@Luiggi似乎在回复我发表的评论时提供了一些帮助here。
注意:这也可以。
private String input;
public Bean(){
this.input= fetchValueFromDatabase();
}
答案 0 :(得分:1)
其实我无法重现你的问题。这对我来说可以。我测试了Mojarra 2.2.8和Apache Tomcat 7.0.47。你有没有看到任何错误?`可能在你的数据库代码中?是否应用了背景样式?
但是我不确定你是否真的需要绑定?您也可以尝试以下方法。
private String input= fetchValueFromDatabase();
public PreInitializeBean(){
}
private String fetchValueFromDatabase() {
String resultValue = "preSetValue";
return resultValue;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
和xml:
<h:inputText value="#{data.input}" maxlength="15" style="background: pink;">
</h:inputText>
我认为这更为传统。