0

I'm using JSF and I'm building a register web page. I'm trying to use a validator to check if the username that the user selected is already existing or not. But I don't find how to query the database to check the username. I've tryed with EJB injection but it is not working, I've got an null pointer exception.

@FacesValidator("usernameUnicityValidator")
public class UsernameUnicityValidator implements Validator {
    @EJB
    private ArticleFacadeLocal articleFacade;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value==null) {
            FacesMessage message = new FacesMessage("The username cannot be empty");
            message.setSeverity(FacesMessage.SEVERITY_FATAL);
            throw new ValidatorException(message);
        }
        if (userFacade.findByUsername((String)value)) {
            FacesMessage message = new FacesMessage("Username already exist");
            throw new ValidatorException(message);
       }
    }
}
claudex
  • 69
  • 6
  • 1
    possible duplicate of [Dependency injection in FacesValidator (JSF Validation)](http://stackoverflow.com/questions/7572335/dependency-injection-in-facesvalidator-jsf-validation) – BalusC Apr 03 '13 at 17:16
  • Yes, it seems that would solve my issue. Thank you. – claudex Apr 03 '13 at 17:28

1 Answers1

0

@EJB injection won't be supported until Faces 2.2/2.3 comes out. See http://arjan-tijms.omnifaces.org/p/jsf-22.html

For JSF2.0/2.1, there isn't really a good alternative at the minute. Typically for this scenario what I do is do this sort of 'validation' in my page's backing bean, then use FacesContext.validationFailed() and push a notification back to the page with FacesContext.addMessage(...). It's not an ideal solution because you're mixing your presentation logic with business logic.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Jonathan S. Fisher
  • 8,189
  • 6
  • 46
  • 84
  • Thank you but BalusC show something I prefer http://stackoverflow.com/questions/7572335/dependency-injection-in-facesvalidator-jsf-validation – claudex Apr 03 '13 at 17:30