gpt4 book ai didi

java - 如何验证 JSF 中的唯一性并向用户发送消息?

转载 作者:行者123 更新时间:2023-12-02 07:17:27 25 4
gpt4 key购买 nike

我需要检查应用程序中字段的唯一性。

我尝试使用 Hibernate @Unique 约束,但它显示了堆栈跟踪,但用户表单中没有错误消息。

我的下一个解决方案是编写一个自定义 validator ,但我认为有更好的解决方案。

在 JSF 中是否有更简单的方法来做到这一点?

(JSF 2.1 + RichFaces)

最佳答案

我为我的基本实体的 JSF 2.1 唯一 key 验证破解了一个快速但肮脏的工作解决方案:

用法:

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

validator :

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

关于java - 如何验证 JSF 中的唯一性并向用户发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14750895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com