简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM