0

快速背景:我在我的网站上使用 primefaces 自定义组件放置了验证码。负责人不喜欢它,因为它太难使用而且客户正在/正在抱怨。我决定我想创建一个简单的组件(即:4 + 9 = 并且用户输入答案)以避免一些垃圾邮件。无需使用图像显示问题,只需使用简单的文本即可。这让我开始研究自定义组件和复合组件(来自这篇文章这篇文章)。

现在,问题不在于临时的基本“验证码样式验证”。它更多的是关于复合组件和支持 bean 的组合。

我要做的是以这种风格创建一个支持 bean:

<cc:interface>

    <cc:attribute name="label" />
<!-- edited -->
    <cc:attribute name="required" />
<cc:attribute name="ident" />

</cc:interface>


<cc:implementation>

    <h:panelGrid columns="3">
        <h:outputText value="#{captcha.text}"/>
        <h:inputText id="#{cc.attrs.ident}" value="#{captcha.entered}" validator="#{captcha.validate}" required="#{cc.attrs.required eq 'true'}" label="#{cc.attrs.label}" />
        <h:message for="captchaAnswer" />
    </h:panelGrid>

    <h:inputHidden value="#{captcha.value}" />

</cc:implementation>

然后我想以这种方式使用这个组件:

<h:form>
    ...
    <tr>
        <td>
            <my:captcha label="Captcha" ident="captcha" required="true"/> <!-- added after suggested comment -->
            <br/>
            <h:message for="captcha" class="error"/>
        </td>
    </tr>
    <tr>
        <td colspan="3" class="center">
            <h:commandButton class="button" value="#{msg['contact.label.send']}" action="#{contact.send}" >
        </h:commandButton>
        </td>
    </tr>
    ...
</h:form>

如何确保在提交时我可以检查我的{#captcha.entered}值是否为所需值,如果不是,则在表单上返回验证消息并阻止它被提交?

captcha支持 bean 将很简单,并且具有值:text、、answer和,entered以及检查 if 的简单函数answer == entered

编辑:(尝试#1) 自定义验证器如下所示

public void validate(FacesContext context, UIComponent toValidate, Object value) {

    System.out.println("validating");

    String input = (String) value;

    //check to see if input is an integer
    //if not we know right away that the value is not good
    if(StringUtils.isNumeric(input)) {
        //if the input is numeric, convert to an integer
        int intValue = new Integer(input).intValue();
        if (intValue != answer) {
            ((UIInput) toValidate).setValid(false);

            FacesMessage message = new FacesMessage("Not a match!!");
            context.addMessage(toValidate.getClientId(context), message);
        }
    }
}

在这种情况下,验证器甚至没有被调用,我也没有收到错误消息。

编辑#2

经过一些工作和评论的提示后,我得到了这个工作。为了获得h:message工作,我需要添加属性ident而不是id. 如果不是,我必须这样引用它:<h:message for="captcha:captcha" />这不是预期的结果。

4

1 回答 1

0

这个问题的主要问题是我无法获得参考。

通过添加属性ident而不是id我让它工作。请参阅有问题的编辑#2

于 2013-01-11T20:11:41.810 回答