我正在Spring Boot上构建项目,并希望添加易于集成的验证。 我的项目有Pojo,如下所示:
public class Employee{
@JsonProperty("employeeInfo")
private EmployeeInfo employeeInfo;
}
EmployeeInfo类如下:
public class EmployeeInfo extends Info {
@JsonProperty("empName")
private String employeeName;
}
信息类如下:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Info {
@JsonProperty("requestId")
protected String requestId;
}
如何使用javax.validation
验证请求ID是否为空我的控制器类如下:
@RequestMapping(value = "/employee/getinfo", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<> getEmployee(@RequestBody Employee employee) {
//need to validate input request here
//for e.g to check if requestId is not blank
}
请求:
{
"employeeInfo": {
"requestId": "",
}
}
答案 0 :(得分:0)
考虑到您正在使用 validation-api :
请尝试使用以下内容验证您的String是否为空或不包含任何空格
@NotBlank
答案 1 :(得分:0)
为了验证控制器方法中的请求参数,您可以使用内置验证器或自定义验证器(您可以使用自定义消息添加任何类型的验证。)
有关如何在spring controller中使用自定义验证的详细信息,Check how to validate request parameters以及如下所示的验证器:
@Component
public class YourValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(Employee.class);
}
@Override
public void validate(Object target, Errors errors) {
if (target instanceof Employee) {
Employee req = (Employee) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employeeInfo.requestId", "YourCustomErrorCode", "yourCustomErrorMessage");
//Or above validation can also be done as
if(req.getEmployeeInfo().getRequestId == null){
errors.rejectValue("employeeInfo.requestId", "YourCustomErrorCode", "YourCustomErrorMessage");
}
}
}
}