如何使用CDI创建Validator

时间:2012-05-10 12:34:16

标签: java jsf jsf-2

我想实现自定义验证器,我可以在其中使用CDI和数据源。我测试了这段代码:

<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
    <h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
        <f:validateLength minimum="0" maximum="15"/>
        <f:validator validatorId="ValidatorController" >
        </f:validator>
        <f:ajax event="blur" render="sessionidMessage" />                                          
    </h:inputText>
    <h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>

这是验证器:

    @FacesValidator("ValidatorController")

    public class FormValidator implements Validator {

        public FormValidator() {
        }

        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            if (value.equals("test")) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  Session ID is already in use, please choose another.", null));
            }
        }
}

此代码工作正常。我还尝试实现此代码,以便将CDI用于验证器:

<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
    <h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
        <f:validateLength minimum="0" maximum="15"/>
        <f:validator binding="#{ValidatorController}" >
            <f:attribute name="type" value="sessionid" />
        </f:validator>
        <f:ajax event="blur" render="sessionidMessage" />                                          
    </h:inputText>
    <h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>

这是验证器:

@Named("ValidatorController")

public class FormValidator implements Validator {

    public FormValidator() {
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value.equals("test")) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "  Session ID is already in use, please choose another.", null));
        }
    }

}

出于某种原因,第二个例子不起作用。

1 个答案:

答案 0 :(得分:0)

你应该更具体,什么失败?它不编译?它没有运行?什么是例外,等等。目前还不清楚你在第二种情况下想要达到的目的。

通常,您不能通过嵌套f:attribute insside将属性传递给f:validator。 使您的代码看起来像这样:

<f:validator binding="#{ValidatorController}" (session id in your case) />
<f:attribute name="type" value="sessionid" />

稍后您可以在组件参数Map:

中搜索组件参数
context.getExternalContext().getRequestParameterMap();