我知道这个问题在其他帖子中也曾出现过,但是在应用助焊剂后,建议的操作不起作用。
我正在使用Spring 4.1.7版本,我想从发布后调用中验证RequestBody。为此,我尝试遵循以下代码集,但未按预期工作。
我的请求正文pojo类。
ParentPojo.class
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
@Validated
public class ParentPojo<T> implements Serializable{
@NotNull
private String cNumber;
@NotNull
private String statusCode;
@NotNull T child;
}
ChildPojo.class
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
@Validated
public class ChildPojo{
@NotNull
private String name;
@NotNull
private String address;
@NotNull
private String pin;
}
控制器:
仅添加方法
@Autowired
@Qualifier("validator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(produces = { "application/json", "application/xml" }, consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = { RequestMethod.POST })
@ResponseStatus(HttpStatus.CREATED)
public Messageresponse<ChildPojo> create(@NotNull(groups = {ParentPojo.class, ChildPojo.class})
@Valid @Validated({ParentPojo.class, ChildPojo.class}) @RequestBody final ParentPojo<ChildPojo> ParentPojo, BindingResult bindingResult) {
System.out.println("new version 8="+bindingResult.hasErrors());
validator.validate(ParentPojo, bindingResult);
if(bindingResult.hasErrors()) {
System.out.println("Non formated form stuff.");
}
return service.create(ParentPojo);
}
@RequestMapping(value = "/{create}", produces = { "application/json", "application/xml" }, consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = { RequestMethod.POST })
@ResponseStatus(HttpStatus.CREATED)
public Messageresponse<ChildPojo> create1(@NotNull @Valid @RequestBody final ParentPojo<ChildPojo> ParentPojo, BindingResult bindingResult) {
System.out.println("new version 8="+bindingResult.hasErrors());
validator.validate(ParentPojo, bindingResult);
if(bindingResult.hasErrors()) {
System.out.println("Non formated form stuff.");
}
return service.create(ParentPojo);
}
应用程序上下文xml:
<mvc:annotation-driven validator="validator">
</mvc:annotation-driven>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
尝试了jar文件:
hibernate-validator-4.3.0.Final
hibernate-validator-4.1.0.Final
hibernate-validator-4.0.2.GA
validation-api-1.1.0.Final
spring-context-4.1.7.RELEASE
但是对于下面的请求,上述所有组合均无效:
缺少以下请求“ pin”中的,并且控制器方法@Valid @RequestBody应该将此请求作为错误请求进行处理。而是接受请求正文并进一步处理。
{
"cNumber" : "ff",
"statusCode" : "ddd",
"child" : {
"name" : "ll",
"address" : "ll"
}
答案 0 :(得分:0)
看看这个问题Here
您需要将子pojo装饰为@Valid
public class ParentPojo<T> implements Serializable{
@NotNull
private String cNumber;
@NotNull
private String statusCode;
@Valid
@NotNull
T child;
}