Wednesday 5 July 2017

Spring MVC Java Config : Part 2 Bean Validation and Exception Handler


It is always good to check the validity and integrity of form data before passing to business logic, let's see how to do it.





1.TOOLS AND ENV

IDE : Spring Tool Suite 3.7.3 
JDK : 1.8 
Tomcat : 8.0.18 
Spring : 4.2.6.RELEASE

 

2. POM.XML

Java Bean Validation API and Bean Validation  Provider (Hibernate) added.



3. SEPARATE ROOT AND WEB CONFIG









4. POJO

We would make this POJO a JPA entity class in following posts when persistence is introduced.




5. DAO


We would have DAO talk to database in the following posts.




6.  BUSINESS LOGIC LAYER






7. TODO CONTROLLER


1. Container will do bean validation on model attribute that marked with @Valid 
2. BindingResult must be declared right after @Valid




8. EXCEPTION HANDLER




@ControllerAdvice  is typically used to define ExceptionHandler , InitBinder and ModelAttribute methods that apply to all RequestMapping methods.


9. WEB PAGE





10. Messages for Validation Error







11. TEST



http://localhost:8080/spring-mvc-bean-validation/anything


http://localhost:8080/spring-mvc-bean-validation/todo/error






12. SOURCE CODE

https://github.com/junjun-dachi/spring-tutorials/tree/master/spring-mvc-bean-validation







No comments:

Post a Comment

Flag Counter