在构造函数或@PostConstruct方法中设置消息 - 可能吗?

时间:2011-03-14 09:54:56

标签: java jsf jsf-2 facelets

是否可以在Managed-Bean的构造函数或@PostConstruct方法中设置消息?

例如:

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>

我可以在Eclipse-Console中看到该消息,但不在页面上,为什么?有没有办法告知用户结果?

2 个答案:

答案 0 :(得分:2)

在放入h:messages

之前尝试放置一些访问jsf beans属性的EL
<h:outputText rendered="#{not empty bean.prop}"  />
<h:messages id="msg" />

而不喜欢这个

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

答案 1 :(得分:0)

我发现如果以这种方式添加/更改Managed-Bean和XHTML文件,将显示该消息:

在Example.java中:

private FacesMessage fm;

public FacesMessage getFm() {
    return fm;
}

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

在example.xhtml中:

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