首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在页面加载过程中添加FacesMessage?使用@PostConstruct似乎不起作用

如何在页面加载过程中添加FacesMessage?使用@PostConstruct似乎不起作用
EN

Stack Overflow用户
提问于 2012-04-18 02:52:59
回答 1查看 15.9K关注 0票数 22

在支持bean的@PostConstruct方法中,我调用了一个EJB,它可能会返回一些我希望通过p:messages显示在页面上的消息。但是,即使我添加了消息,例如FacesContext.getCurrentInstance().addMessage(...),p: FacesMessages也不会使用FacesMessages进行更新。

相反,如果我在页面的某个操作上调用对EJB的调用(假设用户单击页面上的一个按钮,该按钮调用一个调用EJB的方法,然后添加FacesMessage(s)),那么消息标记就会像预期的那样使用p:FacesMessage出现。

如何在@PostConstruct期间添加Faces消息,并在页面最初呈现时显示这些消息?

代码:

Page1Controller.java:

代码语言:javascript
复制
@ManagedBean
public class Page1Controller
{
    @PostConstruct
    public void init()
    {
        FacesContext.getCurrentInstance().addMessage(null, 
            new FacesMessage("Test Message from @PostConstruct"));
    }

    public String getValue()
    {
            return "Some Value";
    }

    public void triggerMessage(ActionEvent event)
    {
            FacesContext.getCurrentInstance().addMessage(null, 
                    new FacesMessage("Test Message from Trigger Button"));      
    }

}

page1.xhtml

代码语言:javascript
复制
   <h:form>
        <p:messages showDetail="true" showSummary="true" autoUpdate="true"/>
        <h:outputText value="#{page1Controller.value}"/>
        <br/>
        <p:commandButton value="Trigger Message" 
                         actionListener="#{page1Controller.triggerMessage}"/>  
   </h:form>
EN

回答 1

Stack Overflow用户

发布于 2017-04-05 22:30:28

您可以收集错误,然后在加载页面的末尾使用primefaces的remoteCommand并使用autorun = true模式显示它。在我的例子中,我有一个viewScope,在xhtml中,我显示了加载到@PostConstruct中的值的列表。如果生成了异常,我将使用remoteCommand将其保存到页面加载结束时的示例中。

代码语言:javascript
复制
private ArrayList<Exception> postConstucError = new ArrayList<>();

@PostConstruct
public void validarAcceso() {
    /**
     * verificar permisos a la vista de coeficientes
     */
    try {
            this.init() //load data;
        } catch (Exception e) {
        System.out.print(e.getMessage());
        this.postConstucError.add(e);
    }
}

 public void showPostConstructError() {
    try {
        for (int i = 0; i < this.postConstucError.size(); i++) {
            JsfUtil.addErrorMessage("Error al cargar datos iniciales: " + postConstucError.get(i).getMessage());
        }
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, "Error: showPostConstructError() " + e.getMessage());
    }
}

xhtml代码

代码语言:javascript
复制
  <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true"/> 
  <h:form>
        <p:remoteCommand id="rcomerror" name="showError" process="@this"  autoRun="true"
                         actionListener="#{mBPresentNinos.showPostConstructError()}" />  
    </h:form>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10197277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档