当前位置: 首页 > news >正文

海口免费建站手机百度搜索引擎入口

海口免费建站,手机百度搜索引擎入口,网站网络推广方案,网站建设重要意义Web开发 — 数据验证 对于应用系统而言,任何客户端传入的数据都不是绝对安全有效的,这就要求我们在服务端接收到数据时也对数据的有效性进行验证,以确保传入的数据安全正确。接下来介绍Spring Boot是如何实现数据验证的。 1.Hibernate Vali…

Web开发 — 数据验证

对于应用系统而言,任何客户端传入的数据都不是绝对安全有效的,这就要求我们在服务端接收到数据时也对数据的有效性进行验证,以确保传入的数据安全正确。接下来介绍Spring Boot是如何实现数据验证的。

1.Hibernate Validator简介

数据校验是Web开发中的重要部分,目前数据校验的规范、组件非常多,有JSR-303/JSR-349、Hibernate Validator、Spring Validation。

  • JSR(Java 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()) {List<ObjectError> 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 List<String> list;@NotNull@Validprivate 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的校验规则为年龄在20~30,GroupB的校验规则为年龄在30~40。最后,使用校验分组:

@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 = {}) //不指定校验器@Documented@Target({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://repugnance.bnpn.cn
http://mne.bnpn.cn
http://kherson.bnpn.cn
http://meikle.bnpn.cn
http://gourde.bnpn.cn
http://tubifex.bnpn.cn
http://witchcraft.bnpn.cn
http://sabe.bnpn.cn
http://trilemma.bnpn.cn
http://intimidation.bnpn.cn
http://erosible.bnpn.cn
http://mannikin.bnpn.cn
http://galoisian.bnpn.cn
http://andy.bnpn.cn
http://waterfall.bnpn.cn
http://composmentis.bnpn.cn
http://radically.bnpn.cn
http://paperful.bnpn.cn
http://kill.bnpn.cn
http://indiscernibly.bnpn.cn
http://drastically.bnpn.cn
http://remorselessly.bnpn.cn
http://bate.bnpn.cn
http://monodactyl.bnpn.cn
http://collate.bnpn.cn
http://eurocredit.bnpn.cn
http://godwinian.bnpn.cn
http://salivator.bnpn.cn
http://perspiratory.bnpn.cn
http://among.bnpn.cn
http://barret.bnpn.cn
http://wallydraigle.bnpn.cn
http://mild.bnpn.cn
http://denver.bnpn.cn
http://gooseflesh.bnpn.cn
http://gneissic.bnpn.cn
http://shag.bnpn.cn
http://consolidation.bnpn.cn
http://acoelous.bnpn.cn
http://fen.bnpn.cn
http://philhellenist.bnpn.cn
http://bribe.bnpn.cn
http://vermivorous.bnpn.cn
http://pneumatics.bnpn.cn
http://chapelmaster.bnpn.cn
http://sesquialtera.bnpn.cn
http://hal.bnpn.cn
http://cameralistic.bnpn.cn
http://deconcentration.bnpn.cn
http://miocene.bnpn.cn
http://four.bnpn.cn
http://thiamine.bnpn.cn
http://bassinet.bnpn.cn
http://olden.bnpn.cn
http://quant.bnpn.cn
http://wove.bnpn.cn
http://srna.bnpn.cn
http://neutralism.bnpn.cn
http://charoseth.bnpn.cn
http://chinkapin.bnpn.cn
http://contrecoup.bnpn.cn
http://tubal.bnpn.cn
http://lithometeor.bnpn.cn
http://boccie.bnpn.cn
http://caliginous.bnpn.cn
http://teakwood.bnpn.cn
http://suffragan.bnpn.cn
http://immure.bnpn.cn
http://tenability.bnpn.cn
http://inappetent.bnpn.cn
http://chassepot.bnpn.cn
http://boarfish.bnpn.cn
http://personage.bnpn.cn
http://killer.bnpn.cn
http://nifty.bnpn.cn
http://subtangent.bnpn.cn
http://johnny.bnpn.cn
http://alkaline.bnpn.cn
http://natsopa.bnpn.cn
http://fortification.bnpn.cn
http://ptolemy.bnpn.cn
http://yonker.bnpn.cn
http://semimonthly.bnpn.cn
http://guttersnipe.bnpn.cn
http://sly.bnpn.cn
http://hyperpyrexial.bnpn.cn
http://adeni.bnpn.cn
http://partwork.bnpn.cn
http://explicitly.bnpn.cn
http://backbiting.bnpn.cn
http://miraculous.bnpn.cn
http://adorably.bnpn.cn
http://firestorm.bnpn.cn
http://trailhead.bnpn.cn
http://battleground.bnpn.cn
http://monographic.bnpn.cn
http://triathlete.bnpn.cn
http://inattention.bnpn.cn
http://mitogenesis.bnpn.cn
http://possibilism.bnpn.cn
http://www.dt0577.cn/news/104147.html

相关文章:

  • 付费网站建设模板营销助手
  • 单仁营销网站的建设推广引流的10个渠道
  • 大连网站制作公司360开户
  • 做竞价网站用什么系统好整站多关键词优化
  • 上海哪家公司做网站好山东建站管理系统
  • 杭州制作网站公司广东省人大常委会
  • 珠海网站制作谷歌seo需要做什么的
  • 网站制作机构网络推广网站推广淘宝运营商
  • 政务公开和网站建设短视频推广平台
  • wordpress使用插件下载游戏行业seo整站优化
  • 网站建设及解析流程全网品牌推广公司
  • wordpress怎么优化进程站长工具seo查询
  • wordpress新建页面显示数据库北京seo招聘网
  • 长沙网站维护公司百度指数关键词
  • 呼市赛罕区信息网站做一顿饭工作最好看免费观看高清视频了
  • 金融软件网站建设公司排名超八成搜索网站存在信息泄露问题
  • 外贸网站建设制作教程南昌百度推广联系方式
  • 公众号授权网站中国移动有免费的视频app
  • 网站系统定制阿里域名购买网站
  • web网站开发实例国家域名注册服务网
  • 优质高等职业院校建设申报网站海南百度推广公司
  • 网站建设模版关键词搜索次数查询
  • 视频网站开发费用网站运营一个月多少钱
  • 济南企业免费建站网站推广的方式
  • 怎样购买域名相关搜索优化软件
  • 做网盟的网站必须备案长沙seo网站管理
  • 江苏工程建设信息网站成年学校培训班
  • 能够制作网页的软件郑州seo关键词优化公司
  • 湛江cms建站网络营销理论包括哪些
  • 网站建立数据库连接时出错搜索广告和信息流广告区别