JSF 2.0中的多组件验证器

在JSF中,没有官方的方法来验证多个组件或字段。 要解决此问题,您需要创建一个自定义验证器。 在本教程中,我们将向您展示两种创建验证器以验证多个组件的非官方方法-密码和确认密码。

两种方式:
1.注册PostValidateEvent ,将验证放入其中。
2.创建一个标准验证器,并通过f:attribute获取其他组件。

此示例在以下技术下进行了测试:

  1. JSF 2.1.11
  2. Tomcat 6、7
  3. Java 1.6
  4. Maven 3

1. PostValidateEvent中的验证

javax.faces.event.PostValidateEvent是一个系统事件,在验证所有组件之后将触发该事件。 这个想法是注册一个PostValidateEvent ,并附加到一个验证方法。 见以下内容:

<f:event listener="#{bean.methodToValidateMultipleFields}" type="postValidate" />
default.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">

<h:body>

<h1>Multiple-Components Validator in JSF 2.0</h1>

  <h:form id="register">

    <h:message for="RegisterGroupPanel" style="color:red;" />

    <h:panelGrid columns="3" id="RegisterGroupPanel">

	<!-- register a PostValidateEvent -->
	<f:event listener="#{user.validatePassword}" type="postValidate" />

	<h:outputLabel for="username" value="Username : " />
	<h:inputText id="username" value="#{user.username}" required="true"
		requiredMessage="Please enter username" />
	<h:message for="username" style="color: red;" />

	<h:outputLabel for="password" value="Password : " />
	<h:inputSecret id="password" value="#{user.password}" required="true"
		requiredMessage="Please enter password" />
	<h:message for="password" style="color: red;" />

	<h:outputLabel for="confirmPassword" value="Confirm password : " />
	<h:inputSecret id="confirmPassword" required="true"
		requiredMessage="Please enter confirm password" />
	<h:message for="confirmPassword" style="color: red;" />

    </h:panelGrid>

	<h:commandButton action="thanks" value="register" />

  </h:form>

</h:body>
</html>

PostValidateEvent ,“侦听器”方法必须具有此签名public void method-name(ComponentSystemEvent event) “。 代码的其余部分应该是不言自明的。

UserBean.java – It has a method to validate password and confirm password components.
package com.mkyong;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean(name = "user")
@SessionScoped
public class UserBean {

	public String username;
	public String password;

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

	public void validatePassword(ComponentSystemEvent event) {

	  FacesContext fc = FacesContext.getCurrentInstance();

	  UIComponent components = event.getComponent();

	  // get password
	  UIInput uiInputPassword = (UIInput) components.findComponent("password");
	  String password = uiInputPassword.getLocalValue() == null ? ""
		: uiInputPassword.getLocalValue().toString();
	  String passwordId = uiInputPassword.getClientId();

	  // get confirm password
	  UIInput uiInputConfirmPassword = (UIInput) components.findComponent("confirmPassword");
	  String confirmPassword = uiInputConfirmPassword.getLocalValue() == null ? ""
		: uiInputConfirmPassword.getLocalValue().toString();

	  // Let required="true" do its job.
	  if (password.isEmpty() || confirmPassword.isEmpty()) {
		return;
	  }

	  if (!password.equals(confirmPassword)) {

		FacesMessage msg = new FacesMessage("Password must match confirm password");
		msg.setSeverity(FacesMessage.SEVERITY_ERROR);
		fc.addMessage(passwordId, msg);
		fc.renderResponse();
			
	  }

	}
}

2.自定义验证器和属性

此方法从本文复制而来- 多个字段的验证器

将“ confirmPassword”组件定义为#{confirmPassword} ,并通过f:attribute附加到“ password”组件。

<h:inputSecret id="password" value="#{user.password}" required="true"
	requiredMessage="Please enter password">

	<f:validator validatorId="passwordValidator" />
	<f:attribute name="confirmPassword" value="#{confirmPassword}" />

</h:inputSecret>

<h:inputSecret id="confirmPassword" required="true"
	binding="#{confirmPassword}"
	requiredMessage="Please enter confirm password" />
default.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">

<h:body>

  <h1>Multiple-Components Validator in JSF 2.0</h1>

  <h:form id="register">

    <h:message for="RegisterGroupPanel" style="color:red;" />

    <h:panelGrid columns="3" id="RegisterGroupPanel">

	<h:outputLabel for="username" value="Username : " />
	<h:inputText id="username" value="#{user.username}" required="true"
		requiredMessage="Please enter username" />
	<h:message for="username" style="color: red;" />

	<h:outputLabel for="password" value="Password : " />
	<h:inputSecret id="password" value="#{user.password}" required="true"
		requiredMessage="Please enter password">
		<f:validator validatorId="passwordValidator" />
		<f:attribute name="confirmPassword" value="#{confirmPassword}" />
	</h:inputSecret>
	<h:message for="password" style="color: red;" />

	<h:outputLabel for="confirmPassword" value="Confirm password : " />
	<h:inputSecret id="confirmPassword" required="true"
		binding="#{confirmPassword}"
		requiredMessage="Please enter confirm password" />
	<h:message for="confirmPassword" style="color: red;" />

    </h:panelGrid>

	<h:commandButton action="thanks" value="register" />

  </h:form>

</h:body>
</html>

一个自定义的验证器类,并通过component.getAttributes获得确认密码component.getAttributes

PasswordValidator.java – JSF Custom validator
package com.mkyong;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component,
		Object value) throws ValidatorException {

	  String password = value.toString();

	  UIInput uiInputConfirmPassword = (UIInput) component.getAttributes()
		.get("confirmPassword");
	  String confirmPassword = uiInputConfirmPassword.getSubmittedValue()
		.toString();

	  // Let required="true" do its job.
	  if (password == null || password.isEmpty() || confirmPassword == null
		|| confirmPassword.isEmpty()) {
			return;
	  }

	  if (!password.equals(confirmPassword)) {
		uiInputConfirmPassword.setValid(false);
		throw new ValidatorException(new FacesMessage(
			"Password must match confirm password."));
	  }

	}
}

3.演示

以上两种解决方案都在做相同的事情,请验证两个组件-密码和确认密码。

没有输入, required="true"被触发。

jsf2 multiple components validator

验证多个组件/字段。 确保密码等于确认密码。

jsf2 multiple components validator

下载源代码

下载它– JSF-Validator-Multiple-Components-Example.zip (27 KB)

参考文献

  1. JSF 2 PostValidateEvent JavaDoc
  2. JSF 2事件列表

翻译自: https://mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值