问题
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