Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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>
      <version>1.1.0.Final</version>
    </dependency>
    
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version...