java - 如何使用 CDI 创建 validator

标签 java jsf jsf-2

我想实现自定义 validator ,在其中可以使用 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>

这是 validator :

    @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));
            }
        }
}

这段代码工作正常。我还尝试实现此代码以便在 validator 中使用 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>

这是 validator :

@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));
        }
    }

}

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

最佳答案

你应该更具体一点,什么失败了?它不编译?它不运行?异常(exception)情况是什么,等等。而且还不清楚您在第二种情况下想要实现什么目标。

一般情况下,您不能通过在内部嵌套 f:attribute 来将属性传递给 f:validator。 让你的代码看起来像这样:

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

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

context.getExternalContext().getRequestParameterMap();

关于java - 如何使用 CDI 创建 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10534111/

相关文章:

java - 音频文件Android

jquery - Primefaces 是否能够从另一个域获取 jquery?

jsf - bean 和 jsf 验证注释 inisde 托管 bean 与实体 bean

jsf - 将 bean 属性绑定(bind)到 JSF 中的元素时出现问题

java - JSF ViewExpiredExceptionHandler NullPointerException

java - 命令按钮问题

java - powershell invoke-expression java程序获取状态

java - 循环方法中的线程

java - 部署maven的问题

forms - 使用 GET 提交 JSF 表单