SpringBoot_Validation
第一步
<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
在对应字段上添加校验规则
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QuartSearchCondition {
private Integer id;
@NotEmpty(message = "name 不能为空")
private String name;
@NotEmpty(message = "chineseName 不能为空")
private String chineseName;
@NotEmpty(message = "value 不能为空")
private String value;
@NotNull(message = "conditionMode 不能为空")
private Integer conditionMode;
@NotNull(message = "conditionType 不能为空")
private Integer conditionType;
private Integer jobId;
}
第三步
@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;
}
}