The following are the steps to apply validations:
- Let's apply validations provided by the hibernate-validator API on Book.java as follows:
public class Book { @NotEmpty @Size(min = 2, max = 30) private String bookName; @Min(150) private long ISBN; @NotEmpty @Size(min = 2, max = 30) private String publication; @NotNull private int price; @NotEmpty @Size(min = 10, max = 50) private String description; @NotEmpty private String author; //default and parameterized constructor //getters and setters }
- Let's update AddBookController.
- Delete the validator data member.
- Delete initBinderMethod.
- Keep the @Valid annotation applied on the Book argument of the addBook() method as it is.
- Remove the bean for validator from books-servlet.xml, as it's no longer required.
- Comment the bean for messageResource from XML; we will use it later on.
- Make sure to have the <mvc:annotation-driven /> entry in book-servlet.xml to enable the framework to consider the annotation in controllers.
- Run the application. Upon submission of the blank form, you will get the following response displaying the default validation messages:
The customization of the messages can be done either by using the message attribute, or by externalizing the messages using the properties file. Let's do them one by one.