您不应该在支持 bean 操作方法中进行验证,而应该在正常的Validator
.
例如
<h:inputText value="#{register.email}" required="true" validator="#{emailValidator}" />
<h:inputSecret binding="#{password}" value="#{register.password}" required="true" />
<h:inputSecret required="true" validator="confirmPasswordValidator">
<f:attribute name="password" value="#{password.value}" />
</h:inputSecret>
...
像#{emailValidator}
这样:
@MangedBean
public class EmailValidator implements Validator {
@EJB
private UserService userService;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
return; // Let required="true" handle.
}
if (userService.existsEmail((String) value)) {
throw new ValidatorException(Messages.createError("Email already exists"));
}
}
}
请注意,EJB 不应在此处抛出异常。只有在出现致命且不可恢复的错误(例如 DB 关闭或错误的表/列定义)时才应该这样做。
confirmPasswordValidator
像这样的东西
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object password = component.getAttributes().get("password");
if (value == null || password == null) {
return; // Let required="true" handle.
}
if (!password.equals(value)) {
throw new ValidatorException(Messages.createError("Password do not match"));
}
}
}