我们知道javax.validation提供了validation-api的jar包实现请求参数校验,避免在业务代码中写一些繁琐的校验逻辑。
以下说明嵌套属性的一种写法。
package com.example.demo.controller;
import com.example.demo.model.ActionParentModel;
import com.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/hello")
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("/test")
public Boolean test(@RequestBody @Valid ActionParentModel req){
return true;
}
}
ActionParentModel.class
package com.example.demo.model;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;
public class ActionParentModel implements Serializable {
@Size(min = 1, max = 2)
private List> updateConds;
public List> getUpdateConds() {
return updateConds;
}
public void setUpdateConds(List> updateConds) {
this.updateConds = updateConds;
}
}
ActionModel .class
package com.example.demo.model;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class ActionModel {
/**
* 条件类型(1:宝马,2:奔驰)
*/
@NotNull
@Range(min = 1, max = 2)
private Integer keyType;
@Pattern(regexp = "\\w+", message = "属性名格式不正确")
private String keyName;
public Integer getKeyType() {
return keyType;
}
public void setKeyType(Integer keyType) {
this.keyType = keyType;
}
public String getKeyName() {
return keyName;
}
public void setKeyName(String keyName) {
this.keyName = keyName;
}
}
List> updateConds; 这里的@Valid 必须放在ActionModel前面,否则校验无效。
注意这里的validation-api须为2.0.1.Final,版本1.1.0.Final是不支持的。
对比两个版本的源码区别
2.0.1.Final:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Valid {
}
1.1.0Final:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Valid {
}
2.0.1.Final多了ElementType.TYPE_USE的支持。
maven依赖
javax.validation
validation-api
2.0.1.Final
org.hibernate.validator
hibernate-validator
6.0.16.Final