您的位置:首页 > 其它

数据校验

2017-05-09 00:00 218 查看
一个应用程序的健壮性很大程度是取决于输入数据的验证是否完善。

TCSF中数据校验是采用实现JSR303的Hibernate Validator和Spring MVC进行结合。

在Spring MVC控制器方法定义form对象为方法参数,并加入参数注解,在其后追加参数BindingResult,如下:

@ResponseBody
@RequestMapping(value = "create", method = RequestMethod.POST)
public ApiResponseEntity create(@Valid StudentForm form, BindingResult result) {
ValidationUtil.validate(result);
this.getService().create(form);
return ApiResponseEntity.buildOK();
}

当请求参数绑定到from对象后,hibernate validator将会对form对象进行数据校验,校验结果会存储在result对象中,在方法体内使用ValidationUtil.validate方法对校验结果进行处理。如果校验失败,validate方法将会抛出一个ValidationException的运行时异常,开发者无需try catch处理,因为TCSF定义了统一的异常处理,当发生校验异常将会向客户端响应如下JSON内容:

{
"code" : "ILLEGAL_ARGUMENT",
"message" : "姓名不能为空"
}

如果开发者需要特别处理,也可以try catch自己进行编码。

目前仅支持对于参数绑定对象的校验,如果是类似于String、Boolean和Integer等控制器方法参数,需要开发者自行进行验证判断:

@ResponseBody
@RequestMapping(value = "create", method = RequestMethod.POST)
public ApiResponseEntity create(@RequestParam(required = true) String name) {
if(StringUtil.isBlank(name)) {
return ApiResponseEntity.buildIllegalArgument("姓名不能为空");
}
this.getService().create(name);
return ApiResponseEntity.buildOK();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TCSF 数据验证