How to show multi error message in jsf while valid

2019-09-14 22:51发布

Based on the answer from this question, i understand that if there is an error, EJB will throw an exception which will be catch in the backing bean and backing bean will show user an error message based on exception its catch.

My question is, what if theres more than one error? How can i show multiple error message to the user, while the EJB can only throw one exception at a time?

For example, at registration form user will need to input email address, name, password, and re-password, and must not be null. If all the data is valid but the given email address is already exist, EJB will throw EntityExistException and the user will be notified that email address is already registered. What if theres multiple error like password and re-password not match and the name is empty? And i want to show these two error to the user. What exception should EJB throw? What approach i can take to achieve this?

Note: the validation must be in EJB

1条回答
你好瞎i
2楼-- · 2019-09-14 23:32

You shouldn't be doing validation in a backing bean action method, but in a normal Validator.

E.g.

<h:inputText value="#{register.email}" required="true" validator="#{emailValidator}" />
<h:inputSecret binding="#{password}" value="#{register.password}" required="true" />
<h:inputSecret required="true" validator="confirmPasswordValidator">
    <f:attribute name="password" value="#{password.value}" />
</h:inputSecret>
...

with the #{emailValidator} being something like this:

@MangedBean
public class EmailValidator implements Validator {

    @EJB
    private UserService userService;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null) {
            return; // Let required="true" handle.
        }

        if (userService.existsEmail((String) value)) {
            throw new ValidatorException(Messages.createError("Email already exists"));
        }
    }

}

Note that the EJB shouldn't throw an exception here. It should only do that when there's a fatal and unrecoverable error such as DB down or wrong table/column definitions.

And the confirmPasswordValidator being something like this

@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Object password = component.getAttributes().get("password");

        if (value == null || password == null) {
            return; // Let required="true" handle.
        }

        if (!password.equals(value)) {
            throw new ValidatorException(Messages.createError("Password do not match"));
        }
    }

}
查看更多
登录 后发表回答