3

I want to display error messages when the user first requested the page. The error is set in the post construct method of the request scoped managed bean like the following:

@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;
    }
}

and then in my JSF page:

<!-- I'm expecting the error you have no credit will be displayed here -->
<h:messages />
<h:form>
    <h:inputText value="#{myBean.name}" />
</h:form>

When run in development stage, the JSF complaints that this is an unhandled messages:

"Project Stage[Development]: Unhandled Messages - You have no credit!"

Can you help me?

Hez
  • 125
  • 2
  • 11

2 Answers2

3

I was experiencing the same issue on WebSphere 7 with MyFaces JSF 2.1.

It appears as though WebSphere is flushing the buffer too early, so that the messages tag is rendered prior to the @PostConstruct method completing. I have not as yet found a way to alter WebSphere's behavior however by placing a getter-method in the managed bean to return an empty string and use a h:ouputText tag to use the value I now have a page which renders my messages.

e.g.

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>
Butney
  • 56
  • 6
2

I solved the same problem by putting the messages after the first declaration of the bean that is expected to produce the message you want to be shown. So in your example above instead of having this:

**<h:messages />**
<h:form>
    <h:inputText value="#{myBean.name}" />
</h:form>

Try to make it like this:

<h:form>
    <h:inputText value="#{myBean.name}" />
</h:form>
**<h:messages />**

Check BalusC's more detailed explanation here: How can I add Faces Messages during @PostConstruct

Hope this helps

Community
  • 1
  • 1
Fritz
  • 1,144
  • 1
  • 13
  • 21