因此,我正在为网站创建注册页面,并希望它检查数据库中是否已存在电子邮件(或用户名)。我可以使用所有其他验证,但是由于某种原因,这不会产生错误消息。
这是我的xhtml:
<div class="form-group mx-auto">
<p:outputLabel for="emailInput" value="Email" indicateRequired="false"></p:outputLabel>
<p:inputText type="text" class="form-control" id="emailInput" value="#{signupBackingBean.email}" required="true" requiredMessage="This field is required" validator="#{signupBackingBean.validateEmail}"></p:inputText>
<p:message for="@previous" display="text" ></p:message>
</div>
这就是我要验证的方式:
public void validateEmail(FacesContext context,
UIComponent component,
Object value) {
if (accountDAO.emailExist(value.toString())){
String msg = "Email is already registered";
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", msg));
}
}
此外,这是对emailExist()的查询(使用easyCriteria):
public boolean emailExist(String emailString) {
try {
QAccount_ qaccount = new QAccount_();
JPAQuery query = new JPAQuery(entityManager);
Account account = query.select(qaccount)
.where(qaccount.email.eq(emailString))
.getSingleResult();
return true;
} catch (NoResultException e) {
return false;
}
}
我相信查询的处理方式有问题。我放了!在验证器的if语句中的表达式之前,我输入的所有电子邮件均收到错误消息。但是,查询已通过我的所有测试。
提前感谢!
因此故障发生在emailExist
方法中。我将其更改为以下代码,一切正常。
public boolean emailExist(String emailString) {
QAccount_ qaccount = new QAccount_();
JPAQuery query = new JPAQuery(entityManager);
List<Account> accounts = query.select(qaccount)
.where(qaccount.email.eq(emailString))
.getResultList();
if (accounts.size() > 0) {
return true;
} else {
return false;
}
}