SpringMVC使用@Valid注解进行数据验证
1.添加相关的Maven依赖
javax.validation
validation-api
1.1.0.Final
2.在@RequestMapping这个注解所在的方法上使用@Valid注解进行数据的校验。
@Override@PostMapping(“/”)
public JsonResult create(@Valid @RequestBody T model, BindingResult result) {
if (result.hasErrors()) {
StringBuilder errorMessage = new StringBuilder();
result.getAllErrors().forEach(objectError -> errorMessage.append(objectError.getDefaultMessage()).append(“、”));
Msg msg =Msg.InsertFailed;
return new JsonResult(msg);
}
return new JsonResult(service.create(model));
}
1、@JsonIgnoreProperties
类注解
作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响
写法将此标签加在model 类的类名上 ,可以多个属性也可以单个属性
//生成json时将name和age属性过滤
@JsonIgnoreProperties({"name"},{"age"})
public class user {
private String name;
private int age;
}
@JsonIgnoreProperties({“name”},{“age”})
publicclassuser{
privateStringname;
privateintage;
}
2、@JsonIgnore
此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。
生成json 时不生成对应 属性
3、@JsonFormat
此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)
4、@Transient
@[email protected]映射,ORM框架将忽略该属性;
如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架默认其注解为@Basic;
//表示该字段在数据库表中没有,一般也可以标注在属性上方
@Transient
public int getAge() {
return 1+1;
}