自定义验证程序,我应该使用FacesContext#addMessage()还是抛出ValidatorException? [英] Custom Validator, should I use FacesContext#addMessage() or throw ValidatorException?

查看:184
本文介绍了自定义验证程序,我应该使用FacesContext#addMessage()还是抛出ValidatorException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在JSF 1.2中实现自定义验证器的正确方法是什么。在我的Validator类中'

I was wondering what is the correct way of implementing the custom Validator in JSF 1.2. In my Validator class'

public void validate(FacesContext context, UIComponent component,Object value) throws   ValidatorException {}

方法,我正在做验证检查,只是添加了 FacesMessage 在无效条件下通过 context.addMessage(new FacesMessage(xxx ...); 实例到上下文。这在我的应用程序中似乎正常工作。但是,我不确定我是否还需要显式地抛出新的ValidatorException()来使JSF正确处理生命周期?或者JSF是否足够聪明以查看上下文中的错误消息管理生命周期?

method, I am doing the validation check and just adding the FacesMessage instance to the context by context.addMessage(new FacesMessage(xxx...); in case of invalid condition. This seems to be working fine in my application. However, I am not sure if I also need to explicitely throw new ValidatorException() for JSF to handle the lifecycle correctly? Or would JSF be smart enough to look at the error messages in context to manage the lifecycle?

推荐答案

您确实应该抛出 ValidatorException 否则,JSF仍将继续处理请求并更新模型值并调用action方法。您不想拥有它。

You should indeed be throwing a ValidatorException. Otherwise JSF will still continue processing the request and update the model values and invoke the action method. You don't want to have it.

请勿手动添加 FacesMessage 。用它构造 ValidatorException ,然后JSF将自动将消息添加到正确的组件中,然后JSF将正确跳过 Update Model Values 调用动作阶段。

Do not manually add the FacesMessage. Construct the ValidatorException with it and JSF will then automatically add the message to the right component and JSF will then correctly skip the Update Model Values and Invoke Action phases.

if (!valid) {
    FacesMessage message = new FacesMessage(SEVERITY_ERROR, "Invalid", null);
    throw new ValidatorException(message);
}

这篇关于自定义验证程序,我应该使用FacesContext#addMessage()还是抛出ValidatorException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆