1

我想实现自定义验证器,我可以在其中使用 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));
        }
    }

}

由于某种原因,第二个示例不起作用。

4

1 回答 1

0

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

通常,您不能通过将 f:attribute 嵌套在内部来将属性传递给 f:validator。使您的代码如下所示:

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

稍后您可以在组件参数映射中搜索组件参数:

context.getExternalContext().getRequestParameterMap();
于 2012-06-07T15:15:35.680 回答