SpringBoot_Validation
第一步
- pom.xml 文件中添加架包
xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
第二步
- 定义实体类
QuartSearchCondition
在对应字段上添加校验规则
java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QuartSearchCondition {
/**
* id
*/
private Integer id;
/**
* 字段名
*/
@NotEmpty(message = "name 不能为空")
private String name;
/**
* 中文名
*/
@NotEmpty(message = "chineseName 不能为空")
private String chineseName;
/**
* 字段值,以json形式存储
* 如:
* ["green","garnett","nick","james","thompson","tom","cally","towns","lavin","wigins"]
* {"gte":10,"lte":50}
*/
@NotEmpty(message = "value 不能为空")
private String value;
/**
* 查询方式:
* 1 match 分词
* 2 terms 多个完全匹配任一个
* 3 term 完全匹配
* 4 range 两者之间
* 5 wildcard 模糊
* 6 being 字段不为空
*/
@NotNull(message = "conditionMode 不能为空")
private Integer conditionMode;
/**
* 字段间关系 1 must 2 mustNot 3 should
*/
@NotNull(message = "conditionType 不能为空")
private Integer conditionType;
/**
* 报表id
*/
private Integer jobId;
}
第三步
Controller
层直接使用,数据就会校验
java
@RestController
@Slf4j
public class QuartSearchController {
@PostMapping("/getQuartSearchValue")
public String getQuartSearchValue(@Valid @RequestBody QuartSearchCondition quartSearchCondition) {
log.info("传参为:{}", quartSearchCondition);
if (ObjectUtils.isEmpty(quartSearchCondition.getValue())) {
return "传参为空!";
}
return "success";
}
@PostMapping("/getQuartSearch")
public List<String> getQuartSearch(@Validated @RequestBody QuartSearchCondition quartSearchCondition, BindingResult result) {
log.info("传参为:{}", quartSearchCondition);
List<String> list = new ArrayList<>();
if (result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
for (ObjectError allError : allErrors) {
list.add(allError.getDefaultMessage());
}
}
return list;
}
}