Validating a form using annotations

In this recipe, you'll learn how to add form validation rules by adding constraints directly in model classes using annotations. For example:

public class User {
  @NotEmpty
  private String firstName;

We'll use constraint annotations from the Java bean annotation API and from Hibernate Validator (which is a project independent of Hibernate ORM).

If the validation fails, the form will be shown again to the user with the errors that are to be fixed.

How to do it…

Add constraint annotations to the model class. Check whether the validation was successful in the controller method. Add error tags in the JSP:

  1. Add the Maven dependencies in pom.xml:
    <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.