[英]How to validate generic bean in REST service?
In my current project I frequently use bulk requests. 在我当前的项目中,我经常使用批量请求。 I have simple
BulkRequest<T>
class: 我有简单的
BulkRequest<T>
类:
import java.util.List;
import javax.validation.constraints.NotNull;
public class BulkRequest<T> {
@NotNull private List<T> requests;
public List<T> getRequests() { return this.requests; }
public void setRequests(List<T> requests) { this.requests = requests; }
}
It very simple to use with other beans, for example: 与其他bean一起使用非常简单,例如:
@RequestMapping(value = "/departments/{departmentId}/patterns",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> post(
final @PathVariable long departmentId,
final @Valid @RequestBody BulkRequest<AddPatternRequest> bulkRequest
) {
...
}
AddPatternRequest
contains own rules for validation and represents only one request, which can be collected to bulk request: AddPatternRequest
包含自己的验证规则,仅代表一个请求,可以将其收集为批量请求:
import javax.validation.constraints.NotNull;
public class AddPatternRequest {
@NotNull private Long pattern;
public Long getPattern() { return this.pattern; }
public void setPattern(Long pattern) { this.pattern = pattern; }
}
But there's a problem. 但是有一个问题。 After the controller receives the bulk request, it validates only
BulkRequest
and checks if requests
collection is null
or not, but I need to validate nested request too. 控制器收到批量请求后,它仅验证
BulkRequest
并检查requests
集合是否为null
,但我也需要验证嵌套请求。
How can I do it? 我该怎么做?
Add @Valid to the requests. 将@Valid添加到请求中。 Like this
像这样
@NotNull
@Valid
private List<T> requests;
Then nested objects are also validated 然后嵌套对象也被验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.