Spring MVC ValidationThe Spring MVC Validation is used to restrict the input provided by the user. To validate the user's input, the Spring 4 or higher version supports and use Bean Validation API. It can validate both server-side as well as client-side applications. Bean Validation APIThe Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations. As Bean Validation API is just a specification, it requires an implementation. So, for that, it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that allows to express and validate application constraints. Validation AnnotationsLet's see some frequently used validation annotations.
Spring MVC Validation ExampleIn this example, we create a simple form that contains the input fields. Here, (*) means it is mandatory to enter the corresponding field. Otherwise, the form generates an error. 1. Add dependencies to pom.xml file.pom.xml 2. Create the bean classEmployee.java 3. Create the controller classIn controller class:
4. Provide the entry of controller in the web.xml fileweb.xml 5. Define the bean in the xml filespring-servlet.xml 6. Create the requested pageindex.jsp 7. Create the other view componentsviewpage.jsp final.jsp Output: Let's submit the form without entering the password. Now, we entered the password and then submit the form. Download Hibernate Validator Jar FileIf you are not using maven, download hibernate validator jar. Next TopicRegular Expression Validation |