如何在使用JSF加载页面时显示消息?

时间:2018-06-18 08:41:22

标签: jsf

当使用JSF单击按钮时,我可以显示错误/信息消息,但是在加载页面时我无法显示消息。

请尝试以下操作。

的index.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form id="componentForm">
            <h:messages errorStyle="color: red" infoStyle="color: green" globalOnly="true" />
                Enter the word Java here:
            <h:inputText id="javaText" value="#{messageController.javaText}" />
            <h:message for="javaText" errorStyle="color: red" infoStyle="color: green" />
            <h:commandButton id="addMessage" action="#{messageController.newMessage}"
                         value="New Message" />
        </h:form>
    </h:body>
</html>

MessageController.java:

@Named(value = "messageController")
@SessionScoped
public class MessageController implements Serializable {

    int hitCounter = 0;
    private String javaText;

    public MessageController() {
        javaText = null;
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Managed Bean Initialized", null);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public void newMessage() {
        String hitMessage = null;
        hitCounter++;
        if (hitCounter > 1) {
            hitMessage = hitCounter + " times";
        } else {
            hitMessage = hitCounter + " time";
        }

        Date currDate = new Date();
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "You've pressed that button " + hitMessage + "! The current date and time: " + currDate, null);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);

        if (getJavaText().equalsIgnoreCase("java")) {
            FacesMessage javaTextMsg = new 
            FacesMessage(FacesMessage.SEVERITY_INFO, "Good Job, that is the correct text!", null);
            FacesContext.getCurrentInstance()
            .addMessage("componentForm:javaText", javaTextMsg);
        } else {
            FacesMessage javaTextMsg = new 
            FacesMessage(FacesMessage.SEVERITY_ERROR, "Sorry, that is NOT the correct text!", null);
            FacesContext.getCurrentInstance()
            .addMessage("componentForm:javaText", javaTextMsg);
        }
    }

    public String getJavaText() {
        return javaText;
    }

    public void setJavaText(String javaText) {
        this.javaText = javaText;
    }

}

除了构造函数创建的一条消息外,每条消息都会正确显示。

我希望在加载页面时显示消息Managed Bean Initialized

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,不幸的是FacesContext仅在页面加载时初始化。

所以当页面初始化时你不能使用FacesContext.getCurrentInstance()。addMessage():(

我尝试了2个解决方案

  • 准备好文件后,请拨打ajax以显示消息

  • 传递字符串消息并显示