Time for action – displaying FacesMessage using <p:messages>

Let us see how to display multiple FacesMessage using <p:messages>:

  1. Create a form with two commandButton elements and the <p:messages/> component using the following code:
    <h:form style="width: 500px; padding-left: 10px;">
      <p:panel header="Messages with All Severity levels">
      <p:messages globalOnly="true" autoUpdate="true"/>
      <p:commandButton value="Show FacesMessages" actionListener="#{messagesController.addMultipleMsgs}"/>
      </p:panel>
    </h:form>
  2. Add FacesMessage in the actionListener method as follows:
    public void addMultipleMsgs()
    {
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sample Info Msg", null));
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Sample Warn Msg", null));
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Sample Error Msg", null));
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL,"Sample Fatal Msg", null));
    }

What just happened?

We added FacesMessage objects with various severity levels in the actionListener method addMultipleMsgs(), and updated the form using autoUpdate="true". Then <p:messages/> displays all of those errors as follows:

What just happened?