捕获ajax请求
我需要检查应用程序中字段的唯一性。
我尝试使用Hibernate @Unique
约束,但它显示了堆栈竞争,但在用户表单中没有错误消息
我的下一个解决方案是编写一个自定义验证器,但我认为还有更好的解决方案。
在JSF中有没有更简单的方法可以做到这一点?
(JSF 2.1+RichFaces)
我为JSF 2.1破解了一个快速、肮脏的工作解决方案,为我的基本实体进行了唯一的密钥验证:
用法:
<p:inputText id="name" value="#{employeesController.currentEmployee.name}">
<f:validator validatorId="uniqueColumnValidator" />
<f:attribute name="currentEntity" value="#{employeesController.currentEmployee}" />
<f:attribute name="uniqueColumn" value="name" />
</p:inputText>
验证器:
@RequestScoped
@FacesValidator("uniqueColumnValidator")
public class UniqueColumnValidator implements Validator, Serializable {
@PersistenceContext
protected EntityManager em;
/**
* generic unique constraint validator for AbstractBaseEntity entities<br />
* requires the following additional attributes on the form element ("<f:attribute>"):<br />
* - "currentEntity" the entity instance (used for getting the class and guid)<br />
* - "uniqueColumn" the column where the new value will be checked for uniqueness
*/
@Override
public void validate(final FacesContext context, final UIComponent comp, final Object newValue) throws ValidatorException {
AbstractBaseEntity currentEntity = (AbstractBaseEntity) comp.getAttributes().get("currentEntity");
String uniqueColumn = (String) comp.getAttributes().get("uniqueColumn");
boolean isValid = false;
try {
em.createQuery(
"FROM " + currentEntity.getClass().getSimpleName()
+ " WHERE " + uniqueColumn + " = :value"
+ " AND guid <> :guid", currentEntity.getClass())
.setParameter("value", value)
.setParameter("guid", currentEntity.getGuid())
.getSingleResult();
} catch (NoResultException ex) {
isValid = true; // good! no result means unique validation was OK!
}
if (!isValid) {
FacesMessage msg = Messages.createError("must be unique", uniqueColumn);
context.addMessage(comp.getClientId(context), msg);
throw new ValidatorException(msg);
}
}
}
您可以通过ajax请求手动验证您的bean。下面给出了手动验证的示例。
ClassValidator<TestClass> classValidator = new ClassValidator<TestClass>(
TestClass.class );
InvalidValue[] invalidValues = classValidator
.getInvalidValues(testObject);
for (InvalidValue invalidValue : invalidValues) {
System. out .println( "Property Name: "
+ invalidValue.getPropertyName() + " Message: "
+ invalidValue.getMessage());
}
您可以使用<a4j:support />
标签
您可以在textfield
上使用<f:ajax />
或onblur
事件,并在您的backingbean中验证所有不是null
的model
值。
<h:message id="errorMessageTag" for="fieldId"/>
<h:inputText id="fieldId" value="#{beanName.modelName.variableName}">
<f:ajax event="blur" listener="#{beanName.property}" render="errorMessageTag" />
</h:inputText>