tags:

views:

1061

answers:

2

Hi!

My page:

...
    <div id="header">
       <!-- content header -->
     </div>
     <div id="content">
       <h:messages />
       <h:ouputText value="#{example.text}" />
     </div>
...

My managedBean:

public class ExampleManagedBean(){
       private String text;


       public String getText(){
           FacesContext.getCurrentInstance().
                   addMessage(null, 
                      new FacesMessage(FacesMessage.SEVERITY_WARN, 
                                       "Warning message...", null));
           return text;
       }

       public void setText(String text){
           this.text = text;
       }
   }

My problem is that the warning message not is rendered in page. Why?

A: 

FacesMessage is send to <h:messages/> during validation phase of JSF lifecycle. In your case getter is used to derive bean property value and no validation is going on, so the message is empty.

In theory you can use setter validation, but this is a well known antipattern.

You can do "by hand" validation, but in a different way

 <div id="content">
    <h:messages />
    <h:form>
        <h:outputText value="#{example.text}" />
        <h:commandButton value="Click" action="#{example.action}"/>
    </h:form>
 </div>

and the action method is

public String action(){
   FacesContext.getCurrentInstance().
        addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_WARN,
                                       "Warning message...", null));
           return null;
}

Much cleaner approach would use built-in or custom validator.

Piotr Kochański
Sorry, but you're completely wrong. The by OP posted code is valid and supposed to work. The FacesMessages are derived during renderresponse, regaredless of where they're been set. The problem lies somewhere else, the OP has yet to clarify it based on the comment of Bozho. Until then it's only shooting in the dark.
BalusC
Yes, there is an <f:view>. The page not is refreshed, because it is the first page.
bblanco
+1  A: 

I have two ideas.

First, the message is added in the getText() getter. If h:messages is rendered before h:outputText, then the message might not be there yet when h:messages is rendered.

Second, messages disappear on redirects.

lexicore