Error messages on page with the <h:messages> in JSF
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));
Michael
Updated on July 09, 2022Comments
-
Michael almost 2 years
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 oneh: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!