Learn Java for Web Development

(Tina Meador) #1

258 CHAPTER 5: Building Java Web Applications with Spring Web MVC



  1. import com.apress.bookstore.model.Book;



  2. public class BookValidator implements Validator {

  3. @Override

  4. public boolean supports(Class clazz) {

  5. return Book.class.equals(clazz);

  6. }



  7. @Override

  8. public void validate(Object obj, Errors errors) {

  9. Book book = (Book) obj;

  10. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bookTitle", "field.required",
    "Required Field");

  11. if (! errors.hasFieldErrors("bookTitle")) {

  12. if (book.getBookTitle().isEmpty())

  13. errors.rejectValue("Title", "", "Cannot be left empty!");

  14. }

  15. }





  16. }


   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



  1. package com.apress.bookstore.controller;



  2. import java.util.List;



  3. import org.springframework.beans.factory.annotation.Autowired;

  4. import org.springframework.stereotype.Controller;

  5. import org.springframework.ui.ModelMap;

  6. import org.springframework.validation.BindingResult;

  7. import org.springframework.web.bind.WebDataBinder;

  8. import org.springframework.web.bind.annotation.InitBinder;

  9. import org.springframework.web.bind.annotation.ModelAttribute;

  10. import org.springframework.web.bind.annotation.RequestMapping;

  11. import org.springframework.web.bind.annotation.RequestMethod;

  12. import org.springframework.web.bind.support.SessionStatus;

  13. import org.springframework.web.context.request.WebRequest;



  14. import com.apress.bookstore.model.Author;

  15. import com.apress.bookstore.model.Book;

  16. import com.apress.bookstore.service.AuthorService;

  17. import com.apress.bookstore.service.BookService;

  18. import com.apress.bookstore.validator.BookValidator;



Free download pdf