1

is it possible to set a message in constructor or @PostConstruct method of a Managed-Bean?

For example:

public class Example {

    @ManagedProperty(value = "#{index.facade}")
    private PersistenceFacade pf;

    public Example() {
    }

    @PostConstruct
    public void doExample() {
        try {
            pf.disconnect();

            ((HttpSession) FacesContext.getCurrentInstance()
                    .getExternalContext().getSession(false)).invalidate();

            setMessage("Successful.");
        } catch (DAOException e) {
            e.printStackTrace();
            setMessage("Error: " + e.toString());
            }
    }

    public void setPf(PersistenceFacade pf) {
        this.pf = pf;
    }

    private void setMessage(String message) {
        FacesMessage fm = new FacesMessage(message);
        FacesContext.getCurrentInstance().addMessage(null, fm);
    }

    public String back() {
        return "/index.xhtml";
    }

example.xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
<h:head>
    <title>Example</title>
</h:head>
<h:body>
    <h1>
        <h:outputText value="Example" />
    </h1>
    <h:form>
        <p>
            <h:commandButton id="back" value="Back"
                action="#{example.back}"></h:commandButton>
        </p>
        <h:messages globalOnly="true" />
    </h:form>
</h:body>
</html>

I can see the message in the Eclipse-Console, but not on the page, why? Is there any way to inform the user about the result?

2 Answers2

2

try to put some EL that access jsf beans properties before putting the h:messages

<h:outputText rendered="#{not empty bean.prop}"  />
<h:messages id="msg" />

and not like this

 <h:messages id="msg" />
 <h:outputText rendered="#{not empty bean.prop}"  />
0

I found out that the message will be shown if I add/change the Managed-Bean and the XHTML-file in this way:

In Example.java:

private FacesMessage fm;

public FacesMessage getFm() {
    return fm;
}

private void setMessage(String message) {
        fm = new FacesMessage(message);
        FacesContext.getCurrentInstance().addMessage(null, fm);
}

In example.xhtml:

<h:messages globalOnly="true" rendered="#{!empty example.fm}" />