在我的应用程序中,我具有以下内容Validator
来验证验证码输入:
@Named(value = "simpleCaptchaValidator")
@RequestScoped
public class SimpleCaptchaValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
Captcha secretCaptcha = (Captcha) session.getAttribute(Captcha.NAME);
// Clear the input field
EditableValueHolder input = (EditableValueHolder) component;
input.resetValue();
// Display an error msg if the entered words are wrong
if (!secretCaptcha.isCorrect(value.toString())) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed!", "You have entered wrong words.");
throw new ValidatorException(msg);
}
}
}
Validator
当用户输入错误的验证码单词时,以上内容对非Ajax请求非常有用。但是,如果用户输入了正确的验证码单词,但在其他组件上验证失败,则不会清除验证码的输入字段。
如果您能告诉我如何解决上述问题,我将不胜感激。
它不起作用,因为EditableValueHolder#resetValue()
在错误的时刻调用了。您应该在调用应用程序阶段(至少在更新模型值阶段之后)而不是在验证阶段进行调用。也就是说,当validate()
方法无例外地返回时,JSF仍将已验证的值设置为组件的本地值。一般而言,当验证阶段失败时,将不会调用更新模型值阶段,并且局部值仍然停留在组件中。
根据到目前为止提供的信息,不可能提出正确的方法。如果这是一个自定义组件,则不要在中写入值encode()
。或者,如果这是现有组件,那么最好的选择是创建一个自定义转换器,该转换器将提交的值存储为自定义组件属性,然后null
在中返回getAsObject()
。然后,在验证器中,只需获取该自定义组件属性作为值即可。万不得已时,请附上一个PhaseListener
可在适当时机重置组件的按钮。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句