带有的消息的页面上的错误消息。

时间:2022-08-29 22:45:05

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

我将在JSF上创建简单的示例。这是小型登录应用程序。我的问题是在我的页面上重复错误信息:

带有的消息的页面上的错误消息。

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

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

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

操作方法登录()在我的支持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?

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

I tried to use the attribute globalOnly:

我尝试使用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 个解决方案

#1


17  

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

如果您正确地将消息添加到您的支持bean中,那么globalOnly开关应该是有效的。在FacesContext.addMessage(…)中,客户机-id必须为null。

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

#1


17  

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

如果您正确地将消息添加到您的支持bean中,那么globalOnly开关应该是有效的。在FacesContext.addMessage(…)中,客户机-id必须为null。

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