【问题标题】:Error messages on page with the <h:messages> in JSFJSF 中带有 <h:messages> 的页面上的错误消息
【发布时间】:2012-06-17 06:59:07
【问题描述】:

我正在 JSF 上创建简单的示例。这是一个小的登录应用程序。我的问题是我的页面上有重复的错误消息:

我的页面上有两个h:message(用于用户名和密码)标签和一个h:messages(全局消息):

<h:form id="loginForm">

   <h:panelGrid columns="3">

       <h:outputText value="Username" />
       <h:inputText id="username" value="#{loginBean.username}" 
                  required="true" requiredMessage="Please enter your username" />
       <h:message for="username" errorClass="errorMessage" /> <!-- Message for username -->

       <h:outputText value="Password" />
       <h:inputSecret id="password" value="#{loginBean.password}" 
                  required="true" requiredMessage="Please enter your password" />
       <h:message for="password" errorClass="errorMessage" /> <!-- Message for password -->


       <h:commandButton value="Login" action="#{loginBean.login}" />

   </h:panelGrid>

   <h:messages styleClass="errorMessage" /> <!-- Global messages -->


</h:form>

我的 backing bean 中的操作方法login()

public String login() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if ("admin".equals(username) && "pass".equals(password)) {
        return "success";
    } else {
        facesContext.addMessage("loginForm", new FacesMessage("Username or password is incorrect"));
        return null;
    }
}

我想仅在这些字段旁边显示关于空用户名或密码的消息,而不是在全局消息中的我的按钮下方。如果密码或用户名不正确,我想在全局消息中打印我的错误来自我的操作方法的消息。我该如何解决这个问题?

我尝试使用属性globalOnly

<h:messages styleClass="errorMessage" globalOnly="true" /> <!-- Global messages -->

但这并没有完全解决我的问题,因为在这种情况下根本不会显示全局消息。

提前致谢!

【问题讨论】:

    标签: java jsf jsf-2 messages


    【解决方案1】:

    如果您在支持 bean 中正确添加消息,globalOnly 开关应该可以工作。 FacesContext.addMessage(...) 中的客户端 ID 必须是 null

    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(message));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2012-03-18
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多