1.前端返回的Json串
{
"studentId":"",
"studentName":""
}
2.使用Student类来接收属性
private String studentId;
private String studentName;
省略setget方法、、、
3.为了限制studentId和studentName属性不为空
需要在Student类中添加注解,引用的包
//引用的包
import org.hibernate.validator.constraints.NotBlank;
@NotBlank(message = "studentId不能为空!")
private String studentId;
@NotBlank(message = "studentName不能为空!")
private String studentName;
省略setget方法、、、
4.在controller中
需要注意的是@valid的注解和BindingResult,一旦不符合验证的要求就会抛出在Student类中的异常。
@ResponseBody
@RequestMapping("/update")
public Object updateStudent(**@Valid** @RequestBody Student student,**BindingResult error**){
if(error.hasErrors()){
BusiLogicException.create().init(error.getFieldError().getDefaultMessage()).raise();
}
int result = ruleDefineBusiService.updateStudent(ruleDefineModel);
return result == 1 ? AjaxResultUtil.success() : AjaxResultUtil.fail("操作失败!");
}
很重要
实际上在studentId上我原来定义的是Long类型,这个时候就得用到下面两个注解。
第一个是将Long类型转变成Json的时候不会缺失数据
第二个是将Json转变成Long,但是总是报错。
@JsonSerialize(using=ToStringSerializer.class)
@JsonDeserialize(using = NumberDeserializers.LongDeserializer.class)