user3127896
user3127896

Reputation: 6563

java ee bean validation

I'm trying to implement user authorization on java ee 7. For validation entered data I use Bean validation annotations.

    @NotNull(message = "Please enter email address")
    @Column(name = "email")
    private String email;

    @NotNull(message = "Please enter password")
    @Size(min = 6, max = 255)
    @Column(name = "password")
    private String password;

Also I have @PrePersist method which hash entered password

    @PrePersist
    public void updatePassword(String password) {
        //some code
    }

Here is a method where I register user:

@EJB
private UserService userService;

public void register() {
        if (userService.getByEmail(email) == null) {
            try {
                userService.register(email, password);

                //log in if users is created
                authController.setEmail(email);
                authController.setPassword(password);
                authController.login();
            } catch (Exception e) {
                setErrorMessage("Validation error");
            }
        } else {
            setErrorMessage("Please choose another email address");
        }
    }

UserService

@Stateless
public class UserService {

    @EJB
    private UserDAO userDAO;

    public void register(String email, String password){
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userDAO.create(user);
    }
}

The problem is if password is null. At first called updatePassword method but not @NotNull annotation over the password field and thus i get NullPointerException. How to make that at first checks validation and then later other methods. Thanks in advance!

Upvotes: 1

Views: 197

Answers (1)

Dejan Paler
Dejan Paler

Reputation: 21

It seems that bean validation is not triggered soon enough.

One way to solve this would be to inject ValidatorFactory into UserService and then validate user object after it is created. Something like this:

@Stateless 
public class UserService {    

    @EJB
    private UserDAO userDAO;

    @Inject
    private ValidatorFactory validatorFactory;

    public void register(String email, String password){
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);

        Set<ConstraintViolation<User>> constraintViolations = validatorFactory.getValidator().validate(user);
        if(constraintViolations.size() > 0){
            // handle error
        }else{
            userDAO.create(user);
        }
    }
}

this answer could be helpful for clarification

Upvotes: 1

Related Questions