【发布时间】:2019-12-11 00:31:24
【问题描述】:
我想用 @Valid 注释验证我的请求正文,但它在 Spring Boot 中不起作用
我在 JAR 文件中有一个请求类,我无法使用两个字段进行修改。一个字段是对象类型。我的控制器类接受这个类对象作为请求体。当我将下面的 JSON 传递给控制器时,验证不起作用。以下是代码示例。
请求类:
public class Request {
Object data;
Map<String, Object> meta;
public <T> T getData() throws ClassCastException {
return (T) this.data;
}
}
另一个类:
public class StudentSignUpRequest {
@NotNull(message = "First Name should not be empty")
@Size(max = 64, message = "FirstName should not exceed 64 characters")
private String firstName;
@NotNull(message = "Last Name should not be empty")
@Size(max = 64, message = "LastName should not exceed 64 characters")
private String lastName;
@NotNull(message = "Email cannot be empty")
@Size(max = 50, message = "Email cannot exceed 50 characters")
@Pattern(regexp = EMAIL_REGEX_PATTERN, message = "Email should contain a valid email address.")
private String email;
// other fields
}
控制器类:
@PostMapping(value = Constants.STUDENT_SIGN_UP)
public Response signUpStudent(@Valid @RequestBody Request request, HttpServletRequest servletRequest) {
// retrieving the actual resource from request payload
StudentSignUpRequest signUpRequest = request.getData(StudentSignUpRequest.class);
// call service to sign-up student
return loginRegistrationService.signUpStudent(signUpRequest);
}
调用代码设置请求如下:
StudentSignUpRequest studentSignUpRequest = new StudentSignUpRequest();
//setter methods
Request payload = new Request();
payload.setData(studentSignUpRequest);
这是我发送的请求:
名字超过 64 个字符:
示例 JSON:
{
"data": {
"firstName": "student111111111111111111111111111111111111111111111111111111111111",
"lastName": "somesurname",
"email": "developer@gmail.com"
}
}
不包括名字的地方:
{
"data": {
"lastName": "somesurname",
"email": "developer@gmail.com"
}
}
这里@Size 和@NotNull 注释都不起作用。
有什么办法吗?
【问题讨论】:
标签: java spring spring-boot jackson bean-validation