Error messages on page with the <h:messages> in JSF

人盡茶涼 提交于 2019-12-21 04:57:34

问题


I'm creating simple example on JSF. It's small Login application. My problem is duplicate error messages on my page:

I have two h:message(for username and password) tags and one h:messages(global messages) on my page:

<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>

Action method login() in my backing bean:

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

I want to display message about empty username or password only next to these fields, not under my button in global messages. And I want to print my error message from my action method in global messages if password or username is incorrect. How can I resolve this?

I tried to use the attribute globalOnly:

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

but it isn't completely solved my problem, because global messages aren't displayed at all in this case.

Thanks in advance!


回答1:


The globalOnly switch should work if you add your messages correctly in your backing bean. The client-id must be null in FacesContext.addMessage(...):

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


来源:https://stackoverflow.com/questions/11029792/error-messages-on-page-with-the-hmessages-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!