Part 2 - Applying validations

The following are the steps to apply validations:

  1. 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 
} 
  1. Let's update AddBookController.
  2. Delete the validator data member.
  3. Delete initBinderMethod.
  4. Keep the @Valid annotation applied on the Book argument of the addBook() method as it is.
  5. Remove the bean for validator from books-servlet.xml, as it's no longer required.
  6. Comment the bean for messageResource from XML; we will use it later on.
  7. Make sure to have the <mvc:annotation-driven /> entry in book-servlet.xml to enable the framework to consider the annotation in controllers.
  8. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.105.239