参数映射数据的校验 -- hibernate-validate

2015-11-09 23:58:49   最后更新: 2015-11-09 23:58:49   访问数量:1021




Hibernate Annotations 是 Bean Validation 的参考实现,提供了 JSR 303 规范中所有内置 constraint 的实现

它支持使用注解的方式进行参数的验证工作,是一个非常强大的参数验证工具

 

maven 引入

首先需要通过 maven 引入项目,增加配置:

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.2.Final</version> </dependency>

 

然后 reimport 即可

 

hibernate-validator 配置

需要在 servlet-config.xml 中加入相关配置:

<!-- 默认的注解映射的支持 --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />

 

 

Model

接下来,我们建立一个用于被检测的 model 类

package com.demo; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; /** * Created by techlog on 15/11/9. */ public class ValidateModel { @NotEmpty private String name; @Range(min=30, max=50, message = "${validatedValue} 岁不符合要求, 年龄必须在 {min} 和 {max} 之间") private String age; @NotEmpty @Email private String email; public void setName(String name){ this.name=name; } public void setAge(String age){ this.age=age; } public void setEmail(String email){ this.email=email; } public String getName(){ return this.name; } public String getAge(){ return this.age; } public String getEmail(){ return this.email; } }

 

可以看到我们在每个字段的上方加上了注解,用于限制他们的取值

这些注解就来源于 hibernate-validate,同时,每个注解我们都可以加上 message 参数,用于定义验证失败后的返回信息,如果没有 message 参数,hibernate-validate 会取默认的说明信息

 

Controller

package com.demo; 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; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; import java.security.NoSuchAlgorithmException; @Controller @RequestMapping(value = "/validate") public class HomeController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(Model model){ if(!model.containsAttribute("contentModel")){ model.addAttribute("contentModel", new ValidateModel()); } return "validatetest"; } @RequestMapping(value="/test", method = {RequestMethod.POST}) public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException { //如果有验证错误 返回到form页面 if(result.hasErrors()) return test(model); return "validatesuccess"; } }

 

 

这个 controller 与我们上一篇日志中的非常类似,使用 ModelAttribute 注解把数据注入到 model 中,同时,它还使用了 Valid 注解,用来声明需要使用 hibernate-validate

 

jsp

  • validatetest.jsp
<%-- Created by IntelliJ IDEA. User: techlog Date: 15/11/9 Time: 下午10:50 To change this template use File | Settings | File Templates. --%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/><br/><br/> name:<form:input path="name" /> <form:errors path="name" style="color:red"></form:errors><br/><br/> age:<form:input path="age" /> <form:errors path="age" style="color:red"></form:errors><br/><br/> email:<form:input path="email" /> <form:errors path="email" style="color:red"></form:errors><br/><br/> <input type="submit" value="Submit" /> </form:form> </body> </html>

 

 

  • validatesuccess.jsp
<%-- Created by IntelliJ IDEA. User: techlog Date: 15/11/9 Time: 下午10:51 To change this template use File | Settings | File Templates. --%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 验证成功! </body> </html>

 

 

运行结果

 

 

可以看到,点击 submit 后,服务端返回了相应的验证信息

<form:errors path="*"></form:errors>

这个标签用于将全部错误信息显示出来

 

主要的验证注解及其说明
注解适用数据类型说明
AssertFalseBoolean, boolean验证注解的元素值是false
AssertTrueBoolean, boolean验证注解的元素值是true
DecimalMax(value=x)BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.验证注解的元素值小于等于@ DecimalMax指定的value值
DecimalMin(value=x)BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.验证注解的元素值小于等于@ DecimalMin指定的value值
Digits(integer=整数位数, fraction=小数位数)BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.验证注解的元素值的整数位数和小数位数上限
Futurejava.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.验证注解的元素值(日期类型)比当前时间晚
Max(value=x)BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.验证注解的元素值小于等于@Max指定的value值
Min(value=x)BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.验证注解的元素值大于等于@Min指定的value值
NotNullAny type验证注解的元素值不是null
NullAny type验证注解的元素值是null
Pastjava.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.验证注解的元素值(日期类型)比当前时间早
Pattern(regex=正则表达式, flag=)String. Additionally supported by HV: any sub-type of CharSequence.验证注解的元素值与指定的正则表达式匹配
Size(min=最小值, max=最大值)String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小
ValidAny non-primitive type(引用类型)验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象
NotEmptyCharSequence,Collection, Map and Arrays验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
Range(min=最小值, max=最大值)CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types验证注解的元素值在最小值和最大值之间
NotBlankCharSequence验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
Length(min=下限, max=上限)CharSequence验证注解的元素值长度在min和max区间内
EmailCharSequence验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

 






技术帖      mvc      龙潭书斋      framework      spring      springmvc      注解      hibernate      validate      校验     


京ICP备15018585号