我非常清楚这一点
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()); }
注意:这也可以.
private String input; public Bean(){ this.input= fetchValueFromDatabase(); }
解决方法
实际上我无法重现你的问题.这对我来说可以.我测试了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>
我认为这更传统.