在我的应用程序中,我有以下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
它会在正确的时刻重置组件。
关于jsf-2 - 如何清除 Validator 类中的输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20001126/