php企业网站建设,长沙网站建设去哪好,做网站要怎么找单,免费宝塔主机Web开发 — 数据验证
对于应用系统而言#xff0c;任何客户端传入的数据都不是绝对安全有效的#xff0c;这就要求我们在服务端接收到数据时也对数据的有效性进行验证#xff0c;以确保传入的数据安全正确。接下来介绍Spring Boot是如何实现数据验证的。
1.Hibernate Vali…Web开发 — 数据验证
对于应用系统而言任何客户端传入的数据都不是绝对安全有效的这就要求我们在服务端接收到数据时也对数据的有效性进行验证以确保传入的数据安全正确。接下来介绍Spring Boot是如何实现数据验证的。
1.Hibernate Validator简介
数据校验是Web开发中的重要部分目前数据校验的规范、组件非常多有JSR-303/JSR-349、Hibernate Validator、Spring Validation。
JSRJava Specification Request规范是Java EE 6中的一项子规范也叫作Bean Validation。它指定了一整套基于bean的验证API通过标注给对象属性添加约束条件。Hibernate Validator是对JSR规范的实现并增加了一些其他校验注解如Email、Length、Range等。Spring Validation是Spring为了给开发者提供便捷对Hibernate Validator进行了二次封装。同时Spring Validation在SpringMVC模块中添加了自动校验并将校验信息封装进了特定的类中。
JSR定义了数据验证规范而Hibernate Validator则是基于JSR规范实现了各种数据验证的注解以及一些附加的约束注解。Spring Validation则是对Hibernate Validator的封装整合。JSR和Hibernate Validator中的常用注解如表所示。 表中包含了Hibernate Validator实现的JSR-303定义的验证注解和Hibernate Validator自己定义的验证注解同时也支持自定义约束注解。所有的注解都包含code和message这两个属性。
Message定义数据校验不通过时的错误提示信息。code定义错误的类型。
Spring Boot是从Spring发展而来的所以自然支持Hibernate Validator和Spring Validation两种方式默认使用的是Hibernate Validator组件。
2.数据校验
使用Hibernate Validator校验数据需要定义一个接收的数据模型使用注解的形式描述字段校验的规则。下面以User对象为例演示如何使用Hibernate Validator校验数据。
2.1 JavaBean参数校验
Post请求参数较多时可以在对应的数据模型Java Bean中进行数据校验通过注解来指定字段校验的规则。下面以具体的实例来进行演示。首先创建Java Bean实体类
public class User {NotBlank(message 姓名不允许为空!)Length(min 2, max 1,message 姓名长度错误姓名长度2-10!)private String name;NotNull(message 年龄不能为空!)Min(18)private int age;NotBlank(message 地址不能为空!)private String address;Pattern(regexp ((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$, message 手机号格式错误)private String phone;Email(message 邮箱格式错误)private String email;//省略get和set方法
}在示例中每个注解中的属性message是数据校验不通过时要给出的提示信息如Email(message“邮件格式错误”)当邮件格式校验不通过时提示邮件格式错误。然后添加数据校验方法 PostMapping(path /check)public String check(RequestBody Valid User user, BindingResult result) {String name user.getName();if(result.hasErrors()) {ListObjectError list result.getAllErrors();for (ObjectError error : list) {System.out.println(error.getCode() _ error.getDefaultMessage());}}return name;}在上面的示例中在RequestBody注解后面添加了Valid注解然后在后面添加了BindingResult返回验证结果BindingResult是验证不通过时的结果集合。
注意BindingResult必须跟在被校验参数之后若被校验参数之后没有BindingResult对象则会抛出BindException。
最后运行验证。
启动项目在postman中请求/user/check接口后台输出了数据验证的结果
Length-密码长度错误密码长度6-20!
Min-最小不能小于18
Length-姓名长度错误姓名长度2-10!通过上面的输出可以看到应用系统对传入的数据进行了校验同时也返回了对应的数据校验结果。
2.2 URL参数校验
一般GET请求都是在URL中传入参数。对于这种情况可以直接通过注解来指定参数的校验规则。下面通过实例进行演示。
Validated
public class UserController {RequestMapping(/query)public String query(Length(min 2, max 1, message 姓名长度错误姓名长度2-10!)RequestParam(name name, required true) String name,Min(value 1, message 年龄最小只能1)Max(value 99, message 年龄最大只能9)RequestParam(name age, required true) int age) {System.out.println(name , age);return name , age;}
}在上面的示例中使用Range、Min、Max等注解对URL中传入的参数进行校验。需要注意的是使用Valid注解是无效的需要在方法所在的控制器上添加Validated注解来使得验证生效。
2.3 JavaBean对象级联校验
对于JavaBean对象中的普通属性字段我们可以直接使用注解进行数据校验那如果是关联对象呢其实也很简单在属性上添加Valid注解就可以作为属性对象的内部属性进行验证验证User对象可以验证UserDetail的字段。示例代码如下
public class User {Size(min 3, max 5, message list的Size在[3,5])private ListString list;NotNullValidprivate Demo3 demo3;
}public class UserDetail {Length(min 5,max 17,message length长度在[5,17]之间)private String extField;
}在上面的示例中在属性上添加Valid就可以对User中的关联对象UserDetail的字段进行数据校验。
2.4 分组校验
在不同情况下可能对JavaBean对象的数据校验规则有所不同有时需要根据数据状态对JavaBean中的某些属性字段进行单独验证。这时就可以使用分组校验功能即根据状态启用一组约束。Hibernate Validator的注解提供了groups参数用于指定分组如果没有指定groups参数则默认属于javax.validation.groups.Default分组。
下面通过示例演示分组校验。首先创建分组GroupA和GroupB示例代码如下
public interface GroupA {
}
public interface GroupB {
}在上面的示例中我们定义了GroupA和GroupB两个接口作为两个校验规则的分组。然后创建实体类Person并在相关的字段中定义校验分组规则示例代码如下
public class User {NotBlank(message userId不能为空,groups {GroupA.class})
/**用户id*/private Integer userId;NotBlank(message 用户名不能为空,groups {GroupA.class})/**用户id*/private String name;Length(min 30,max 40,message 必须在[30,40],groups {GroupB.class})Length(min 20,max 30,message 必须在[20,30],groups {GroupA.class})/**用户名*/private int age;
}在上面的示例中userName字段定义了GroupA和GroupB两个分组校验规则。GroupA的校验规则为年龄在2030GroupB的校验规则为年龄在3040。最后使用校验分组
RequestMapping(/save)
public String save(RequestBody Validated({GroupA.class, Default.class}) Person person, BindingResult result) {System.out.println(JSON.toJSONString(result.getAllErrors()));
return success;在上面的示例中在Validated注解中增加了{GroupA.class,Default.class}参数表示对于定义了分组校验的字段使用GroupA校验规则其他字段使用默认规则。
3.自定义校验
Hibernate Validator支持自定义校验规则。通过自定义校验规则可以实现一些复杂、特殊的数据验证功能。下面通过示例演示如何创建和使用自定义验证规则。
3.1 声明一个自定义校验注解
首先定义新的校验注解CustomAgeValidator示例代码如下 Min(value 18, message 年龄最小不能小于18)Max(value 120, message 年龄最大不能超过120)Constraint(validatedBy {}) //不指定校验器DocumentedTarget({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})Retention(RetentionPolicy.RUNTIME)public interface CustomAgeValidator {String message() default 年龄大小必须大于18并且小于123;Class?[] groups() default {};Class? extends Payload[] payload() default {};}在上面的示例中我们创建了CustomAgeValidator自定义注解用于自定义年龄的数据校验规则。
3.2 使用自定义校验注解
创建自定义校验注解CustomAgeValidator之后在User的age属性上使用自定义组合注解示例代码如下
public class User {NotBlank(message 姓名不允许为空!)Length(min 2,max 10,message 姓名长度错误姓名长度2-10!)private String name;CustomAgeValidatorprivate int age;NotBlank(message 地址不能为空!)private String address;Pattern(regexp ((13[-9])|(14[5,7,9])|(15([-3]][5-9]))|(166)(17[.1,3,5,6,7,8])l(18[0-9])I(19[8|9]))\\d{8}$, message 手机号格式错误)private String phone;Email(message 邮箱格式错误)private String email;//省略get和set
}在上面的示例中我们在需要做特殊校验的age字段上添加CustomAgeValidator自定义注解这样age字段就会使用我们自定义的校验规则。 文章转载自: http://www.morning.xzkgp.cn.gov.cn.xzkgp.cn http://www.morning.xprzq.cn.gov.cn.xprzq.cn http://www.morning.wlddq.cn.gov.cn.wlddq.cn http://www.morning.rdfq.cn.gov.cn.rdfq.cn http://www.morning.yrctp.cn.gov.cn.yrctp.cn http://www.morning.tmnyj.cn.gov.cn.tmnyj.cn http://www.morning.zxcny.cn.gov.cn.zxcny.cn http://www.morning.tkryt.cn.gov.cn.tkryt.cn http://www.morning.wdskl.cn.gov.cn.wdskl.cn http://www.morning.xkyqq.cn.gov.cn.xkyqq.cn http://www.morning.bnfrj.cn.gov.cn.bnfrj.cn http://www.morning.ftdlg.cn.gov.cn.ftdlg.cn http://www.morning.dztp.cn.gov.cn.dztp.cn http://www.morning.zdmlt.cn.gov.cn.zdmlt.cn http://www.morning.qsxxl.cn.gov.cn.qsxxl.cn http://www.morning.zsyrk.cn.gov.cn.zsyrk.cn http://www.morning.qrpx.cn.gov.cn.qrpx.cn http://www.morning.lrmts.cn.gov.cn.lrmts.cn http://www.morning.mszls.cn.gov.cn.mszls.cn http://www.morning.nqmhf.cn.gov.cn.nqmhf.cn http://www.morning.mswkd.cn.gov.cn.mswkd.cn http://www.morning.tgqzp.cn.gov.cn.tgqzp.cn http://www.morning.27asw.cn.gov.cn.27asw.cn http://www.morning.hmpxn.cn.gov.cn.hmpxn.cn http://www.morning.tpps.cn.gov.cn.tpps.cn http://www.morning.fwblh.cn.gov.cn.fwblh.cn http://www.morning.pdxqk.cn.gov.cn.pdxqk.cn http://www.morning.gblrn.cn.gov.cn.gblrn.cn http://www.morning.nppml.cn.gov.cn.nppml.cn http://www.morning.lltdf.cn.gov.cn.lltdf.cn http://www.morning.tytly.cn.gov.cn.tytly.cn http://www.morning.xjnjb.cn.gov.cn.xjnjb.cn http://www.morning.zlgth.cn.gov.cn.zlgth.cn http://www.morning.rqgq.cn.gov.cn.rqgq.cn http://www.morning.kfyqd.cn.gov.cn.kfyqd.cn http://www.morning.xqzrg.cn.gov.cn.xqzrg.cn http://www.morning.qxdrw.cn.gov.cn.qxdrw.cn http://www.morning.iiunion.com.gov.cn.iiunion.com http://www.morning.zympx.cn.gov.cn.zympx.cn http://www.morning.zxgzp.cn.gov.cn.zxgzp.cn http://www.morning.gfprf.cn.gov.cn.gfprf.cn http://www.morning.dxrbp.cn.gov.cn.dxrbp.cn http://www.morning.qfqld.cn.gov.cn.qfqld.cn http://www.morning.yqfdl.cn.gov.cn.yqfdl.cn http://www.morning.rdnpg.cn.gov.cn.rdnpg.cn http://www.morning.kqxng.cn.gov.cn.kqxng.cn http://www.morning.sdktr.com.gov.cn.sdktr.com http://www.morning.fjgwg.cn.gov.cn.fjgwg.cn http://www.morning.ffbl.cn.gov.cn.ffbl.cn http://www.morning.drmbh.cn.gov.cn.drmbh.cn http://www.morning.wwkft.cn.gov.cn.wwkft.cn http://www.morning.slwqt.cn.gov.cn.slwqt.cn http://www.morning.btlsb.cn.gov.cn.btlsb.cn http://www.morning.nkrmh.cn.gov.cn.nkrmh.cn http://www.morning.ftmly.cn.gov.cn.ftmly.cn http://www.morning.bfcxf.cn.gov.cn.bfcxf.cn http://www.morning.pjtnk.cn.gov.cn.pjtnk.cn http://www.morning.lnwdh.cn.gov.cn.lnwdh.cn http://www.morning.rqqkc.cn.gov.cn.rqqkc.cn http://www.morning.wzknt.cn.gov.cn.wzknt.cn http://www.morning.vattx.cn.gov.cn.vattx.cn http://www.morning.qbfs.cn.gov.cn.qbfs.cn http://www.morning.frfpx.cn.gov.cn.frfpx.cn http://www.morning.pmftz.cn.gov.cn.pmftz.cn http://www.morning.bdwqy.cn.gov.cn.bdwqy.cn http://www.morning.crdtx.cn.gov.cn.crdtx.cn http://www.morning.ns3nt8.cn.gov.cn.ns3nt8.cn http://www.morning.fmdvbsa.cn.gov.cn.fmdvbsa.cn http://www.morning.fbzyc.cn.gov.cn.fbzyc.cn http://www.morning.zwdrz.cn.gov.cn.zwdrz.cn http://www.morning.rwjh.cn.gov.cn.rwjh.cn http://www.morning.gbpanel.com.gov.cn.gbpanel.com http://www.morning.cknws.cn.gov.cn.cknws.cn http://www.morning.tlzbt.cn.gov.cn.tlzbt.cn http://www.morning.mgnrc.cn.gov.cn.mgnrc.cn http://www.morning.hotlads.com.gov.cn.hotlads.com http://www.morning.iknty.cn.gov.cn.iknty.cn http://www.morning.fcwb.cn.gov.cn.fcwb.cn http://www.morning.rlpmy.cn.gov.cn.rlpmy.cn http://www.morning.qqxmj.cn.gov.cn.qqxmj.cn