在 JSF 2.0 中,如何覆盖所需的消息?我正在使用 Primefaces。这是我的代码:
<h:body>
<p:growl id="growl" showDetail="true"/>
<h:panelGroup layout="block" styleClass="login-div">
<h:form id="login">
<p:panel header="Login">
<h:panelGrid columns="2">
<p:outputLabel for="username" value="Username" />
<p:inputText id="username" value="#{authController.username}"
autocomplete="off" required="true"
requiredMessage="Username is required" />
<p:outputLabel for="password" value="Password" />
<p:password id="password" value="#{authController.password}"
autocomplete="off" required="true"
requiredMessage="Password is required" />
</h:panelGrid>
<p:commandButton id="submit" value="Login"
actionListener="#{authController.login}" update=":growl" />
</p:panel>
</h:form>
</h:panelGroup>
<p:ajaxStatus styleClass="ajaxLodingStatus">
<f:facet name="start">
<p:graphicImage value="/resources/images/loading.gif" />
</f:facet>
<f:facet name="complete">
<p:outputLabel value="" />
</f:facet>
</p:ajaxStatus>
</h:body>
现在
Growl
显示:“需要用户名”作为摘要和详细信息 FacesMessage
。密码字段也是如此。现在从命令按钮的
actionListener
中,当登录尝试失败时,我以我想要的方式显示:getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid Credential"));
但我想显示“无效输入”作为摘要,“需要用户名”作为详细信息。
如果我从后端验证这两个输入字段并将
FacesMessage
添加为:if(username == null || username.trim().length() == 0) {
getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid input", "Username is required."));
}
它显示了我需要的东西。但是这样就不需要在输入组件中指定
required="true"
属性了。但是我想使用这个
required
属性也想自定义 FacesMessage
在 Growl
中的显示方式。我怎样才能做到这一点?更新:
这是我的支持 bean:
@ManagedBean(name = "authController")
@ViewScoped
public class AuthController extends BaseWebController implements Serializable {
private static final long serialVersionUID = 2894837128903597901L;
private String username;
private String password;
public AuthController() {
super();
}
public void login(ActionEvent event) {
getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid Credential"));
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
目前
actionaListener
只有在有一些输入时才会触发。否则,当字段为空时,Growl
将显示:点击登录按钮后:
如show-case所示
我想要的是,当输入用户名无法按要求验证时,
Growl
将显示:对于输入密码:
我怎样才能做到这一点?是否可以?
最佳答案
我找到了解决方案:
我需要自定义验证错误消息。
我已经创建了 messages.properties 文件,我在其中写了:
javax.faces.component.UIInput.REQUIRED=Invalid input.
javax.faces.component.UIInput.REQUIRED_detail={0} is required.
并在 faces-config 中将其注册为:
com.edfx.adb.common.properties.messages
我得到了这个:
我还从输入组件中删除了
requiredMessage
属性。一些有用的链接:
关于jsf-2 - 如何自定义 Primefaces' Growl 所需的验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13776654/