258 CHAPTER 5: Building Java Web Applications with Spring Web MVC
- import com.apress.bookstore.model.Book;
- public class BookValidator implements Validator {
- @Override
- public boolean supports(Class clazz) {
- return Book.class.equals(clazz);
- }
- @Override
- public void validate(Object obj, Errors errors) {
- Book book = (Book) obj;
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bookTitle", "field.required",
"Required Field"); - if (! errors.hasFieldErrors("bookTitle")) {
- if (book.getBookTitle().isEmpty())
- errors.rejectValue("Title", "", "Cannot be left empty!");
- }
- }
- }
Lines 19 to 23: Typical validations in the application
The controller named AddBookController is updated for the validation, as shown in Listing 5-51.
Listing 5-51. Updating the AddBookController
- package com.apress.bookstore.controller;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.ModelMap;
- import org.springframework.validation.BindingResult;
- import org.springframework.web.bind.WebDataBinder;
- import org.springframework.web.bind.annotation.InitBinder;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.support.SessionStatus;
- import org.springframework.web.context.request.WebRequest;
- import com.apress.bookstore.model.Author;
- import com.apress.bookstore.model.Book;
- import com.apress.bookstore.service.AuthorService;
- import com.apress.bookstore.service.BookService;
- import com.apress.bookstore.validator.BookValidator;