我有一个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; } }
JSF页面
<?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。
答案 0 :(得分:2)
它正在工作,因为它应该工作。如果验证失败,则不应调用setter。如果需要,可以使用以下命令禁用bean验证:
<f:validateBean disabled="true"/>