简体   繁体   中英

Spring @Validated and @InitBinder

I'm trying to validate my form using a Spring validator, with @Validated .

However, I'm confused why I need to specify the Validator in an @InitBinder .

Here is my relevant code snippets from the controller:

@InitBinder("organisationForm")
private void initBinder(WebDataBinder binder) {
    binder.setValidator(new OrganisationFormValidator());
}

@RequestMapping(value = "/addOrganisation", method = RequestMethod.POST)
public String addOrganisationPost(@Validated @ModelAttribute("organisationForm") OrganisationForm organisationForm, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        return "configuration/addOrganisation";
}

This works fine but I will need to specify an @InitBinder for each of my requests.

Spring has a way of registring all the convertors like so:

@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
     ConversionServiceFactory.registerConverters(getConverters(), 
     formatterRegistry);
}

Is there not a "Validation service" in Spring that looks through all the validators and chooses the right one, perhaps using the supports method enforced by the Spring Validator interface:

public boolean supports(final Class<?> clazz) {
    return OrganisationForm.class.isAssignableFrom(clazz);
}

Just seems strange this doesn't exist in Spring. Have I misunderstood something?

You can use @ControllerAdvice to add validators to your init Binders and you can specify Model Attributes and ExceptionHandler.

If you want to use validators through out the controller (or through out the specific list of controllers) you can specify controller classes to it by using its attributes.

@ControllerAdvice(assignableTypes = { Controller1.class, Controller2.class})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM