【问题标题】:How to display FacesMessage from PostConstruct method of a request scoped bean? [duplicate]如何从请求范围 bean 的 PostConstruct 方法显示 FacesMessage? [复制]
【发布时间】:2011-09-04 00:33:27
【问题描述】:

我想在用户第一次请求页面时显示错误消息。错误是在请求范围的托管 bean 的 post 构造方法中设置的,如下所示:

@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!"

你能帮帮我吗?

【问题讨论】:

    标签: jsf


    【解决方案1】:

    我在使用 MyFaces JSF 2.1 的 WebSphere 7 上遇到了同样的问题。

    WebSphere 似乎过早地刷新缓冲区,因此消息标记在 @PostConstruct 方法完成之前呈现。我还没有找到改变 WebSphere 行为的方法,但是通过在托管 bean 中放置一个 getter 方法来返回一个空字符串并使用 ah: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

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 2014-08-03
        • 2013-01-21
        • 1970-01-01
        相关资源
        最近更新 更多