English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Spring MVC validation is used to limit the input provided by users. To validate user input, Spring 4or higher version supporting and using Bean Validation API. It can validate both server-side and client-side applications at the same time.
Bean Validation API is a Java specification that can be used to apply constraints to object models through annotations. Here, we can validate length, numbers, regular expressions, etc. In addition, we can also provide custom validation.
Since Bean Validation API is just a specification, it needs to be implemented. Therefore, for this, it uses Hibernate Validator. Hibernate Validator is fully compatible with JSR-303/309Implementation, allowing expression and validation of application constraints.
Let's take a look at some commonly used validation comments.
Comment | Description |
@NotNull | It determines that the value cannot be empty. |
@Min | Ensure that the number must be equal to or greater than the specified value. |
@Max | Ensure that the number must be equal to or less than the specified value. |
@Size | @Size |
determines that the size must be equal to the specified value. | @Pattern |
Spring MVC validation example*In this example, we have created a simple form containing input fields. Here, (
、Add dependencies to the pom.xml file.
<!-- .//https:/mvnrepository.com/pom.xml/spring-org.springframework --> validator webmvc/<groupId>org.hibernate.validator< <groupId>org.springframework<-<artifactId>spring/<artifactId>validator< <version>5<artifactId>jstl<1<artifactId>jstl<1webmvc</version> </dependency> <!-- .//https:/mvnrepository.com/.RELEASE</org.apache.tomcat-tomcat --> validator jasper/<groupId>org.hibernate.validator< <groupId>org.apache.tomcat<-<artifactId>tomcat/<artifactId>validator< <version>9.0.12</version> </dependency> <!-- .//https:/mvnrepository.com/alpha/alpha-jasper< --> validator jstl/<groupId>org.hibernate.validator< api-<artifactId>servlet/<artifactId>validator< <version>3api<-.0-1</version> </dependency> <!-- .//https:/mvnrepository.com/alpha/javax.servlet --> validator jstl/<groupId>org.hibernate.validator< <groupId>javax.servlet</<artifactId>validator< <version>1<artifactId>jstl<2</version> </dependency> <!-- .//https:/mvnrepository.com/artifact/org.hibernate.validator-hibernate --> validator <dependency>/<groupId>org.hibernate.validator< <artifactId>hibernate-validator</<artifactId>validator< <version>6.0.13.Final</version> </dependency>
Employee.java
package com.w3codebox; import javax.validation.constraints.Size; public class Employee { private String name; @Size(min=1,message="required") private String pass; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
In the controller class:
@ValidAnnotations apply validation rules to the provided object. BindingResult The interface includes the validation result.
package com.w3codebox; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class EmployeeController { @RequestMapping("/hello") public String display(Model m) { m.addAttribute("emp", new Employee()); return "viewpage"; } @RequestMapping("/helloagain") public String submitForm(@Valid @ModelAttribute("emp") Employee e, BindingResult br) { if(br.hasErrors()) { return "viewpage"; } else { return "final"; } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Provide support for component scanning --> <context:component-scan base-package="com.w3codebox" /> <!--Provide support for conversion, formatting and validation --> <mvc:annotation-driven/> <!-- Define Spring MVC view resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
index.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <body> <a href="hello">Click here...</a> </body> </html>
viewpage.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <style> .error{color:red} </style> </head> <body> <form:form action="helloagain" modelAttribute="emp"> Username: <form:input path="name"/> <br><br> Password(*): <form:password path="pass"/> <form:errors path="pass" cssClass="error"/><br><br> <input type="submit" value="submit"> </form:form> </body> </html>
final.jsp
<html> <body> Username: ${emp.name} <br><br> Password: ${emp.pass} </body> </html>
Output:
Let's submit the form without entering the password.
Now, we enter the password and then submit the form.