2011-05-28 112 views
2

我想在用戶第一次請求頁面時顯示錯誤消息。該錯誤是在請求後構建方法設定範圍內管理的bean如下所示:如何從請求作用域bean的PostConstruct方法顯示FacesMessage?

@RequestScoped 
public class MyBean { 

    private String name; 

    @PostConstruct 
    public void init() { 
     // some validations here 
     FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "You have no credit!"); 
     FacesContext context = FacesContext.getCurrentInstance(); 
     context.addMessage(null, message); 
     context.renderResponse(); 
    } 

    public String getName() { 
     return name; 
    } 
} 

,然後在我的JSF頁面:

<!-- I'm expecting the error you have no credit will be displayed here --> 
<h:messages /> 
<h:form> 
    <h:inputText value="#{myBean.name}" /> 
</h:form> 

當處於發展階段運行中,JSF投訴這是一個未處理的消息:

"Project Stage[Development]: Unhandled Messages - You have no credit!" 

你能幫我嗎?

回答

2

我在使用MyFaces JSF 2.1的WebSphere 7上遇到同樣的問題。

看起來好像WebSphere正在過早清空緩衝區,以便在@PostConstruct方法完成之前呈現消息標記。我還沒有找到一種方法來改變WebSphere的行爲,但是通過在託管bean中放置一個getter-method來返回一個空字符串並使用h:ouputText標記來使用該值,我現在有一個呈現我的消息的頁面。

例如

BackingBean.class

@ManagedBean 
@RequestScopped 
public class BackingBean { 
    public String getEmptyString { return ""; } 
} 

BackingBean.xhtml

<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:f="http://java.sun.com/jsf/core"> 
<h:head></h:head> 
<body> 
<h:outputText value="#{backingBean.emptyString"/> 

... 

</body> 
</html> 
2

我通過將消息,預計將產生你想要的消息bean的第一次申報後解決同樣的問題被顯示。的所以在你上面的例子而不是這樣的:

**<h:messages />** 
<h:form> 
    <h:inputText value="#{myBean.name}" /> 
</h:form> 

儘量做到這樣的:

<h:form> 
    <h:inputText value="#{myBean.name}" /> 
</h:form> 
**<h:messages />** 

檢查BalusC的更詳細的解釋在這裏: How can I add Faces Messages during @PostConstruct

希望這有助於