一个应用程序的健壮性很大程度是取决于输入数据的验证是否完善。
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();
}