页面上包含< h:messages>的错误消息在JSF中 [英] Error messages on page with the <h:messages> in JSF
问题描述
我在JSF上创建了一个简单的例子。这是一个小的登录应用程序。我的问题是我的页面上出现重复的错误消息:
I'm creating simple example on JSF. It's small Login application. My problem is duplicate error messages on my page:
我有两个 h:消息
(用于用户名和密码)标签和一个 h:消息
(全局消息)在我的页面上:
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>
行动方法 login()
在我的支持bean:
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?
我试图使用属性 globalOnly
:
<h:messages styleClass="errorMessage" globalOnly="true" /> <!-- Global messages -->
但它并没有完全解决我的问题,因为全局消息根本不显示在此case。
but it isn't completely solved my problem, because global messages aren't displayed at all in this case.
提前致谢!
推荐答案
globalOnly
如果在支持bean中正确添加消息,切换应该有效。客户端ID必须 null
in FacesContext.addMessage(...)
:
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));
这篇关于页面上包含< h:messages>的错误消息在JSF中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!