PrimeFaces 验证器属性方法中的 NPE

问题描述

我尝试使用验证器属性验证 p:selectOneMenu,但在验证方法中,对象的值为空。我不明白为什么它是空的,有人可以帮助我。我使用的是 PrimeFaces 6.2。

我的 xhtml 是:

<p:selectOneMenu id="somFieldType"
                 widgetvar="somFieldType"
                 converter="entityConverter"
                 required="false"
                 value="#{paramDetail.article_field_type}"
                 validator="#{detailArticleBean2.isTypeValid}"
                 ... >
    <f:selectItem itemLabel="#{i18n['avocado.general.seleccionar']}" itemValue="0"/>
    <f:selectItem itemLabel="#{i18n['avocado.general.texto']}" itemValue="1"/>
    ...
</p:selectOneMenu>

在我的 bean 中,我只打印值:

public void isTypeValid(FacesContext ctx,UIComponent component,Object value) throws ValidatorException {
    System.out.println(value.toString());
}

控制台返回错误

javax.el.ELException: /Ref/Art/artDetail.xhtml @165,67 validator="#{detailArticleBean2.isTypeValid}": java.lang.NullPointerException
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)

非常感谢您的帮助。

解决方法

您的值为 null,因此您不能应用 .toString()。使用类似:

public void isTypeValid(FacesContext ctx,UIComponent component,Object value) throws ValidatorException {
    if (value == null) {
        // Value is unset; don't validate
        return;
    }
    // Value is set; do validation
    ...
}

另见: