【发布时间】:2019-08-25 18:26:41
【问题描述】:
我是 Spring Boot 新手,我对请求字段验证有疑问。 我想出了如何在字段级别使用注释来指定自定义错误消息:
public class EmployeeRequest {
@NotEmpty( message = "field name cannot be empty" )
@NonNull
private String name;
@NotEmpty( message = "field address cannot be empty" )
@NonNull
private String address;
}
但是为了使用这些注释,我必须为每个请求类中的每个字段指定错误消息。 另外由于某种原因,我得到的回复不是很整洁:
"org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'employeeRequest' on field 'name': rejected value [null]; codes [NotEmpty.employeeRequest.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employeeRequest.name,name]; arguments []; default message [name]]; default message [provide a name]"
假设所有字段都必须是NotEmpty 和NonNull,是否有更优雅和通用的方法来对每个请求进行此类字段验证?
public class EmployeeController {
@PostMapping("/test")
@ResponseBody
public EmployeeResponse testMethod(@RequestBody EmployeeRequest request) {
genericFieldsValidatorForAllRequests(request);
doSomeStuffIfRequestIsValid(request);
}
谁能提供一些想法如何实现该请求验证器?
【问题讨论】:
标签: java spring spring-boot