[英]Java bean validation not working with web init binder
I have a controller looks like this:我有一个控制器看起来像这样:
@RestController
@RequestMapping(value="/api/events")
public class EventController{
@Inject
private EventValidator eventValidator;
@InitBinder
@Qualifier("eventValidatior")
private void initBinder(WebDataBinder binder){
binder.setValidator(eventValidator);
}
@PostMapping()
public ResponseEntity<EventModel> save(@Valid @RequestBody EventRequest request, BindingResult result){
if(result.hasErrors()){
//some validation
}
//some other logic
}
}
Then i have a EventRequest
pojo:然后我有一个
EventRequest
pojo:
public class EventRequest{
private String eventName;
@Valid
@NotNull
private List<Event> events;
//setters and getters
}
In my controller, I have 2 types of validation, the InitBinder
, and also java bean validation (JSR-303) that use @NotNull
in EventRequest class.在我的控制器中,我有 2 种类型的验证,
InitBinder
和在 EventRequest 类中使用@NotNull
java bean 验证(JSR-303)。
The problem is, if I have BindingResult result
in the controller, the @NotNull
annotation won't work.问题是,如果我有
BindingResult result
在控制器中, @NotNull
注释将无法正常工作。 And even the cascaded validation in Event
class is not working too.甚至
Event
类中的级联验证也不起作用。
Why is that, how can I have both 2 types of validation?为什么会这样,我怎么能同时拥有两种类型的验证?
Tried to add this but still not working尝试添加此但仍然无法正常工作
@Configuration
public class ValidatorConfig {
@Bean
public LocalValidatorFactoryBean defaultValidator() {
return new LocalValidatorFactoryBean();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
binder.setValidator(eventValidator);
will replace other registered validators.将替换其他已注册的验证器。
Change to:改成:
binder.addValidators(eventValidator);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.