3
votes

In the JSF project I'm working Exceptions thrown by Beans are usually handled by JSF redirecting the user to an error page, but when they are raised inside a Bean validation method, JSF handles them displaying in the relative <h:message> tag the Exception message, instead.

I would like that Exceptions raised in validation methods be handled as the other Exceptions raised from Beans are. Is there a way to achieve that?

The kind of validation I'm using is through backing-bean validator method, for example in JSF page:

<h:inputText value="#{Bean.field}" validator="#{Bean.validate}" />

and, in backing bean code:

public void validate(FacesContext context, UIComponent component, Object value){
   // validation logic here
}

Thanks, Andrea

1
Why would you want to do this? This is not user friendly. The user has to face a complete page change and the user has to navigate back to the form somehow and possibly also need to fill all fields once again. By the way, be careful with the terminology, this is not "bean validation". Bean validation is part of JSR303 API and it are those javax.validation.constraints.* annotations like @NotNull, @Size, etc.BalusC
I'll pay more attention with terminology, thanks! I'd like the application follow distinct behaviors when (1) the validation process outcome is 'invalid' or when (2) the validation process throws Exception. For example, checking if a String the user submitted is already present on DB could "go wrong" in two different ways: (1)the String is already on DB, then the validation outcome is 'invalid' and I want JSF behave exactly as is doing now (display the message in <h:message>) (2)the query raises an Exception, in this case I want to navigate to an error page (and, in case, log the Exception).avalori
Ohh, now I understand you. Well, why don't you just use a normal Validator class which you attach by its ID?BalusC
Thanks this solved my problem! I didn't know that JSF handles Exception differently in validator methods and in Validator classesavalori

1 Answers

1
votes

This is "by design".

Transform that validator into a fullworthy class which implements Validator. Any exceptions other than ValidatorException thrown in there will result in a HTTP 500 error page.

E.g.

public class MyValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value) {
        // validation logic here
    }

}

which you register as <validator> in faces-config.xml

<validator>
    <validator-id>myValidator</validator-id>
    <validator-class>com.example.MyValidator</validator-class>
</validator>

and use as follows in the inputs

<h:inputText ... validator="myValidator" />

or

<h:inputText ...>
    <f:validator validatorId="myValidator" />
</h:inputText>