When doing web development, it is often necessary to verify the data sent by the client to prevent the data from being illegal. The data check supported by SPRINGMVC is the JSR303 standard, which is verified by annotating the annotation @NotNull @Max on the Bean's properties. JSR303 provides a lot of annotation excuses, and SPRINGMVC for these validations is to use Hibernate implementations, so we need to add a validator package for hibernate:
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version></dependency>
The spring configuration file reads as follows:
<?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" xmlns:p= "http://www.springframework.org/schema/p" 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 "> <context:annotation-config/> <context:component-scan base-package=" org.zero01 "/> <mvc:annotation-driven/> <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver "p:prefix="/"p:suffix=". JSP "/></beans>
Hibernate provides additional validation annotations in addition to the JSR303 standard. The following table is a validation note supported by JSR303:
Hibernate Validator Additional annotations:
Let's write a small demo to illustrate how to use it. For example, if I want to verify that some fields cannot be empty, then you can use @NotNull
this annotation, as in the following example:
package org.zero01.test;import javax.validation.constraints.NotNull;public class UserRegister { @NotNull(message = "用户名不能为空") private String userName; @NotNull(message = "密码不能为空") private String password; @NotNull(message = "联系地址不能为空") private String address; @NotNull(message = "电话号码不能为空") private String phone; ...getter and setter...
In the controller's method parameters, it is necessary to obtain the validation error information by declaring the Bindingresult parameter, and then using @Valid
annotations to configure which Pojo object needs to be verified, the controller code is as follows:
Package Org.zero01.test;import Org.springframework.stereotype.controller;import Org.springframework.ui.Model; Import Org.springframework.validation.bindingresult;import Org.springframework.validation.fielderror;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import javax.validation.Valid; @Controllerpublic class Test { @RequestMapping (value = "/test.do", method = Requestmethod.get)//Note that the @Valid and Bindingresult are paired and the formal parameter order is fixed (one after the previous), Otherwise it will return 400 status code public String test (@Valid userregister userregister, Bindingresult Bindingresult, model) {// Determine if there is an exception if (Bindingresult.haserrors ()) {System.out.println ("Client's request data exception, all exceptions are as follows:"); Remove all exception objects for (Fielderror fieldError:bindingResult.getFieldErrors ()) {//Print exception fields and exception information System.out.println (Fielderror.getfield () + ":" + fielderror.getdefaultmessage ()); } return "REgister "; } return "index"; }}
Using Postman for access, no parameters are written:
The console output results are as follows:
客户端的请求数据异常,所有的异常如下:address : 联系地址不能为空userName : 用户名不能为空password : 密码不能为空phone : 电话号码不能为空
Let's take a look at the other common annotations below:
package org.zero01.test;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.Length;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;public class UserRegister { @NotNull(message = "用户名不能为空") private String userName; @NotNull(message = "密码不能为空") @Length(max = 12, min = 6, message = "密码长度需在6-12位之间") private String password; @NotNull(message = "联系地址不能为空") private String address; @NotNull(message = "电话号码不能为空") // 指定正则表达式验证格式 @Pattern(regexp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\\\d{8}$", message = "电话号码格式错误") private String phone; @Email(message = "邮箱格式错误") private String email; @Size(max = 10, min = 1, message = "成绩单列表长度需在1-10之间") public List resultList; ...getter and setter...
The controller code is the same as before, slightly.
Access using Postman, as follows:
The console output results are as follows:
客户端的请求数据异常,所有的异常如下:address : 联系地址不能为空userName : 用户名不能为空password : 密码长度需在6-12位之间phone : 电话号码格式错误email : 邮箱格式错误resultList : 成绩单列表长度需在1-10之间
All of the above are verified for all fields, what if I want some fields to be verified or verified separately? At this point we need to go to the packet verification, first write an interface:
package org.zero01.test;public interface Group {}
Then add the groups attribute to the annotation on the field that needs to be grouped, the value of which is the interface class we defined above, as in the following example:
package org.zero01.test;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.Length;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;public class UserRegister { // groups 属性用于指定分组,值为一个接口类 @NotNull(message = "用户名不能为空", groups = Group.class) private String userName; @NotNull(message = "密码不能为空", groups = Group.class) @Length(max = 12, min = 6, message = "密码长度需在6-12位之间", groups = Group.class) private String password; @NotNull(message = "联系地址不能为空") private String address; @NotNull(message = "电话号码不能为空") @Pattern(regexp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\\\d{8}$", message = "电话号码格式错误") private String phone; @Email(message = "邮箱格式错误") private String email; ...getter and setter...
The controller code is as follows:
Package Org.zero01.test;import Org.springframework.stereotype.controller;import Org.springframework.ui.Model; Import Org.springframework.validation.bindingresult;import Org.springframework.validation.fielderror;import Org.springframework.validation.annotation.validated;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import javax.validation.Valid; @Controllerpublic class Test { @RequestMapping (value = "/test.do", method = Requestmethod.get)//grouping, you need to use the validated annotation to specify the interface public String test (@Va Lidated (Group.class) userregister userregister, Bindingresult Bindingresult, model model) {if (bindingresult.haser Rors ()) {System.out.println ("Client's request data exception, all exceptions are as follows:"); For (Fielderror fieldError:bindingResult.getFieldErrors ()) {System.out.println (Fielderror.getfield () + " : "+ fielderror.getdefaultmessage ()); } return "register"; } RetuRN "Index"; }}
Access way and before consistent, slightly.
The console output results are as follows:
客户端的请求数据异常,所有的异常如下:password : 密码长度需在6-12位之间userName : 用户名不能为空
As above, from the print results in the console, you can see that only password and username two fields were validated because we specified the Groups property only in the annotations on both fields. So the group validation is just the validation of the specified group of fields, and this group is divided by interfaces.
Use the data validation component in Springmvc--hibernate-validator