Lately I had problems with displaying a FacesMessage. I suspected that it was due to creating it inside a property get-method. As a proof I created a simple demo application.

1
2
3
4
5
6
7
8
9
10
11
public class CreateFacesMessageController {
  public String newFacesMessage() {
      new FacesMessageSupport().error("TEST");
      return "success"
  }

  public String getFacesMessage() {
      System.out.println("get-method");
      return newFacesMessage();
  }
}

The class above contains an action method that creates FacesMessage instance and adds it to the FacesContext through some helper class. A get-method (for pseudo property facesMessage) calls this action method.

A JSP view is using these methods to show the effect described.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="UTF-8" ?>

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
  xmlns:c="http://java.sun.com/jsp/jstl/core"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:a4j="http://richfaces.org/a4j"
  xmlns:rich="http://richfaces.org/rich">

  <jsp:directive.page contentType="text/html; charset=UTF-8" />
  <f:view>
      <h:form id="form">
          <rich:panel>
              <rich:messages />
          </rich:panel>
          <rich:panel>
              <f:facet name="header">
                  <h:outputText value="Create faces message example" />
              </f:facet>
              <h:panelGroup>
                  <h:panelGrid>
                      <h:commandButton value="Message"
                          action="#{createFacesMessageController.newFacesMessage}" />

                      <h:outputText value="#{createFacesMessageController.facesMessage}" />
                  </h:panelGrid>
              </h:panelGroup>
          </rich:panel>
      </h:form>
  </f:view>
</jsp:root>

The JSP contains a button that triggers the action method, every time it is clicked a faces message is shown. It also shows the property facesMessage which is bound to the method getFacesMessage.

So one would think that every time the view is show, it also produces a faces message on top of the form - it doesn’t. Here is why:

As a result the messages have alread been rendered when the new faces message is created. You only have 2 choices to remedy. Either you move the messages tag to the very bottom of the form or you make sure that any method that is possibly creating a faces message is invoked in an earlier phase than the RENDER_RESPONSE phase!

Comments