Custom Validator, should I use FacesContext#addMessage() or throw ValidatorException?

别说谁变了你拦得住时间么 提交于 2019-12-10 23:07:25

问题


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 {}

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?


回答1:


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.

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


来源:https://stackoverflow.com/questions/10354089/custom-validator-should-i-use-facescontextaddmessage-or-throw-validatorexcep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!