如果电子邮件已存在于数据库中,我正在尝试使用验证程序检查注册。为此我写这样的表格:
<h:form>
...
<h:inputText id="email" class="form-control" value="#{usersBean.email}">
<f:validator binding="#{existenceEmailValidator}"/>
</h:inputText>
<h:message for="email"/>
...
</h:form>
我还有一个ExistenceEmailValidator类:
package com.ml.validators;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.ml.service.UsersService;
@ManagedBean
@RequestScoped
public class ExistenceEmailValidator implements Validator {
private static final String EMAIL_EXISTE_DEJA = "Cette adresse email est déjà utilisée";
@ManagedProperty( "#{usersService}" )
private UsersService usersService;
@Override
public void validate( FacesContext context, UIComponent component, Object value ) throws ValidatorException {
String email = (String) value;
try {
if ( usersService.existingMail( email ) ) {
System.out.println( "It throws !" );
throw new ValidatorException(
new FacesMessage( FacesMessage.SEVERITY_ERROR, EMAIL_EXISTE_DEJA, null ) );
} else {
}
} catch ( Exception e ) {
}
}
public UsersService getUsersService() {
return usersService;
}
public void setUsersService( UsersService usersService ) {
this.usersService = usersService;
}
}
问题在于,当我尝试提交表单时,ExistenceEmailValidator中的Sysout会在必要时打印“它抛出”,因此似乎会异常抛出异常。但是,在每种情况下,即使电子邮件地址已存在,表单也会提交,用户也会在数据库中注册。
那么,我的验证器有什么问题?我正确使用它吗?
感谢您的回答!
答案 0 :(得分:2)
你确实正确地抛出ValidatorException
。但是你会立即抓住它并用空挡块完全压制它。请参阅下面的评论。
try {
if ( usersService.existingMail( email ) ) {
System.out.println( "It throws !" );
throw new ValidatorException(
new FacesMessage( FacesMessage.SEVERITY_ERROR, EMAIL_EXISTE_DEJA, null ) );
} else {
}
} catch ( Exception e ) {
// Here the ValidatorException is being caught.
// And you're doing nothing with it.
// So, code continues as if nothing exceptional happened.
}
摆脱那个try-catch。这没有意义。让异常去,JSF可以处理它。
if ( usersService.existingMail( email ) ) {
System.out.println( "It throws !" );
throw new ValidatorException(
new FacesMessage( FacesMessage.SEVERITY_ERROR, EMAIL_EXISTE_DEJA, null ) );
}
答案 1 :(得分:-1)
您可以直接使用自定义验证器。
BaluC已在以下链接中给出了您的需求答案: JSF 2.0 validation in actionListener or action method
在bean属性上使用绑定是不好的做法:
How does the 'binding' attribute work in JSF? When and how should it be used?