Using tha Java Validation API

The user registration shown in the previous post has one very visible issue, there is no validation at all. The user could enter whatever value in each required field and the web app happily register it. Using Java Validation we could easily solve this problem.

We need to add an implementation of the javax.validation validation API, the Hibernate validator is a good candidate. So I add its dependency to my Spring Web App POM configuration file:
Then I modify the Spitter bean (in the sense of plain Java Bean), annotating its properties so to impose the rules I want the registration to observe.
For instance, I want the first name to be not null and having a size in [2 .. 30]:
@Size(min = 2, max = 30)
private String firstName;
NotNull and Size are standard Java Validation annotations. Since I use the Hibernate implementation of that JSR, I can use a non-standard, hibernate specific annotation to enforce that the email field represents a valid e-mail address:
private String email;
These checks are enforced in the controller. I change the processRegistration() method in this way:
@RequestMapping(value = "/register", method = POST)
public String processRegistration(@Valid Spitter spitter, Errors errors) {  // 1
    if (errors.hasErrors()) {  // 2
        return "registerForm";
    };  // 3
    return "redirect:/spitter/" + spitter.getUsername();
1. The Spitter input parameter is tagged with the Valid Java Validation annotation, in this way I'm saying to the Hibernate Validator to check its fields accordingly to the annotations specified on this data members. Any error on the validation is pushed in the Errors object.
2. In a real app I would do much more than simply check if there is any validation error. For sure we need to say something to the user, so to help him to correct his mistakes. And it would be probably a good idea to log them.
3. Only if no validation error is detected we go on saving the user and giving a confirmation to the caller.

Reference: Validating form, from Spring in Action, Fourth Edition by Craig Walls. Chapter five, section 4.2.

The complete Java Spring Web App project is on GitHub.

No comments:

Post a Comment