我有一个 Java Web 7 项目,我想在每个 p:ajax
事件的支持 bean 中直接在实体实例上写入 JSF 组件值。只要我在实体属性之一上添加 JSR 303 验证约束(例如 @Size(min=5)
),就可以正常工作。只要违反约束,就不再在具有约束的属性上设置该值。根据 NetBeans 调试器不会调用 setter;另一个属性工作得很好,这让我相信我已经隔离了问题。我想在需要时执行验证,从而根据需要获取无效值集。如何实现这一目标?
在我的最小可重现示例中,我有实体 MyEntity
(JPA 和 JSR 303 注释)
@Entity public class MyEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Size(min = 5) private String property1; private String property2; public MyEntity() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProperty1() { return property1; } public void setProperty1(String property1) { this.property1 = property1; } public String getProperty2() { return property2; } public void setProperty2(String property2) { this.property2 = property2; } }
a JSF page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p:inputText value="#{myManagedBean.myEntity.property1}">
<p:ajax/>
</p:inputText>
<p:inputTextarea value="#{myManagedBean.myEntity.property2}">
<p:ajax/>
</p:inputTextarea>
<p:commandButton value="Save">
<p:ajax listener="#{myManagedBean.onSaveButtonClicked}"/>
</p:commandButton>
</h:form>
</h:body>
</html>
和一个支持 bean
@ManagedBean @SessionScoped public class MyManagedBean { private String value; private String textAreaValue; private MyEntity myEntity = new MyEntity(); public MyManagedBean() { } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getTextAreaValue() { return textAreaValue; } public MyEntity getMyEntity() { return myEntity; } public void setMyEntity(MyEntity myEntity) { this.myEntity = myEntity; } public void setTextAreaValue(String textAreaValue) { this.textAreaValue = textAreaValue; } public void onSaveButtonClicked(AjaxBehaviorEvent event) { System.out.println("value: "+value); System.out.println("textAreaValue: "+textAreaValue); System.out.println("myEntity: "+myEntity); } }
示例可以在 https://github.com/krichter722/jsf-skip-entity-validation 找到。我正在使用 Primefaces 6.0。
最佳答案
它正在按预期工作。如果验证失败,则不应调用 setter。如果您愿意,可以使用以下方法禁用 bean 验证:
<f:validateBean disabled="true"/>
关于ajax - 如何强制执行 p :inputText value to be set through p:ajax if the JSR 303 validation constraint is violated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498851/