Java Reference
In-Depth Information
7. import com.apress.bookstore.model.Book;
8.
9. public class BookValidator implements Validator {
10. @Override
11. public boolean supports(Class clazz) {
12. return Book.class.equals(clazz);
13. }
14.
15. @Override
16. public void validate(Object obj, Errors errors) {
17. Book book = (Book) obj;
18. ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bookTitle", "field.required",
"Required Field");
19. if ( ! errors.hasFieldErrors("bookTitle")) {
20. if (book.getBookTitle().isEmpty())
21. errors.rejectValue("Title", "", "Cannot be left empty!");
22. }
23. }
24.
25.
26. }
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.
3. import java.util.List;
4.
5. import org.springframework.beans.factory.annotation.Autowired;
6. import org.springframework.stereotype.Controller;
7. import org.springframework.ui.ModelMap;
8. import org.springframework.validation.BindingResult;
9. import org.springframework.web.bind.WebDataBinder;
10. import org.springframework.web.bind.annotation.InitBinder;
11. import org.springframework.web.bind.annotation.ModelAttribute;
12. import org.springframework.web.bind.annotation.RequestMapping;
13. import org.springframework.web.bind.annotation.RequestMethod;
14. import org.springframework.web.bind.support.SessionStatus;
15. import org.springframework.web.context.request.WebRequest;
16.
17. import com.apress.bookstore.model.Author;
18. import com.apress.bookstore.model.Book;
19. import com.apress.bookstore.service.AuthorService;
20. import com.apress.bookstore.service.BookService;
21. import com.apress.bookstore.validator.BookValidator;
22.
 
Search WWH ::




Custom Search