我对InputText有两个要求:
我使用的是Primefaces 4.0,JSF 2.2和Glassfish 4以及Java 7
我的代码目前看来是这样的
Example.xhtml
<h:form>
<p:inputText id="value" value="#{myBean.value}" >
<p:ajax event="keyup" update="example" process="@this" />
<f:validator binding="#{uniqueValueValidator}" />
</p:inputText>
<h:outputText id="example" value="#{myBean.value}">
<p:commandButton value="Save" action="#{myBean.saveValue}"/>
</form>
MyBean.java
@Named
@RequestScoped
public class MyBean {
@Inject
private DBService service;
private String value;
//getter, setter
public String saveValue() {
service.saveValue(value);
return "showall";
}
}
UniqueValueValidator.java
@Named
public class UniqueValueValidator implements Validator {
@Inject
private DBService service;
@Override
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
if(service.isValueNotUnique(value.toString()) {
// throw ValidatorException
}
}
}
我现在的问题是,在每个keyup-event上验证该值并调用数据库。但我想仅在提交表单时验证该值。
我的第一个解决方案是将验证移到saveValue
方法中。
public String saveValue() {
if(service.isValueNotUnique(value) {
// add a FacesMessage
return null;
} else {
service.saveValue(value);
return "showall";
}
}
但是我认为在一种方法中混合验证代码和逻辑代码并不是一种好的做法。
所以我希望你有一个更好的解决方案;)
答案 0 :(得分:3)
问题在于inputText组件中的ajax标记:
<p:ajax event="keyup" update="example" process="@this" />
这意味着您要在每个keyup事件上提交组件。并且每次都会调用验证器。
可能的解决方法是将验证器移动到另一个组件,遵循用于验证多个组件的相同技术:
在facelets页面中添加一个使用uniqueValueValidator
的inputHidden:
<h:form id="formId" >
<p:inputText id="value" value="#{myBean.value}" >
<p:ajax event="keyup" update="example" process="@this" />
</p:inputText>
<h:inputHidden id="hidden">
<f:validator validatorId="uniqueValueValidator" />
</h:inputHidden>
<p:message for="hidden" />
<p:commandButton value="Save" action="#{myBean.saveValue}" process="@form" update="@form"/>
</h:form>
<强> UniqueValueValidator 强>:
@Named
@FacesValidator("uniqueValueValidator")
public class UniqueValueValidator implements Validator {
@Inject
private DBService service;
@Override
public void validate(FacesContext context, UIComponent component, Object obj) {
Object inputValue = ((UIInput) context.getViewRoot().findComponent("formId:value")).getSubmittedValue();
if(service.isValueNotUnique((String) inputValue) {
// throw ValidatorException
}
}
}
}
与您的方法一样,此方法意味着每个keyup事件上的内容客户端 - 服务器 - 客户端。如果没有必要,您可以使用javascript方法来避免它,如其他答案所述。
<强>链接强>
答案 1 :(得分:0)
您可以在p:inputText中删除ajax请求,只需使用jquery将输入值复制到inputtext中,如下所示:
<h:form id="myForm">
<p:inputText id="value" value="#{myBean.value}" onkeyup="$("#myForm\\:example").html($(this).val()">
<f:validator binding="#{uniqueValueValidator}" />
</p:inputText>
<h:outputText id="example" value="#{myBean.value}">
<p:commandButton value="Save" action="#{myBean.saveValue}"/>
</form>