Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring validation for RequestBody parameters bound to collections in Controller methods

I have

An Entity:

package org.ibp.soq;

public class MyEntity {

    private String field1;
    private String field2;

    //..getters and setters

}

Validator for the entity:

package org.ibp.soq;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class MyEntityValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return MyEntity.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyEntity myEntity = (MyEntity) target;
        // Logic to validate my entity
        System.out.print(myEntity);
    }

}

and

The REST controller with bulk PUT method:

package org.ibp.soq;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/myEntity")
public class MyEntityRestResource {

    @Autowired
    private MyEntityValidator myEntityValidator;

    @InitBinder
    protected void initBinder(final WebDataBinder binder) {
        binder.addValidators(this.myEntityValidator);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public void bulkCreate(@RequestBody @Valid List<MyEntity> myEntities) {
        // Logic to bulk create entities here.
        System.out.print(myEntities);
    }
}

When I make a PUT request to this resource with following request body:

[
  {
    "field1": "AA",
    "field2": "11"
  },

  {
    "field1": "BB",
    "field2": "22"
  }
]

The error I get is:

"Invalid target for Validator [org.ibp.soq.MyEntityValidator@4eab617e]: [org.ibp.soq.MyEntity@21cebf1c, org.ibp.soq.MyEntity@c64d89b]"

I can understand that this is because MyEntityValidator "supports" single MyEntity validation, not validation for ArrayList<MyEntity>.

MyEntityValidator works perfectly if I have single MyEntity object in request body and a corresponding controller method with @RequestBody @Valid MyEntity myEntity parameter.

How can the validator setup I have used, be extended for supporting validation of collection of MyEntity's ?

like image 574
Naymesh Mistry Avatar asked Dec 01 '15 03:12

Naymesh Mistry


2 Answers

The solution is to create a custom Validator for Collection and a @ControllerAdvice that registers that Validator in the WebDataBinders.

Validator:

import java.util.Collection;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 * Spring {@link Validator} that iterates over the elements of a 
 * {@link Collection} and run the validation process for each of them
 * individually.
 *   
 * @author DISID CORPORATION S.L. (www.disid.com)
 */
public class CollectionValidator implements Validator {

  private final Validator validator;

  public CollectionValidator(LocalValidatorFactoryBean validatorFactory) {
    this.validator = validatorFactory;
  }

  @Override
  public boolean supports(Class<?> clazz) {
    return Collection.class.isAssignableFrom(clazz);
  }

  /**
   * Validate each element inside the supplied {@link Collection}.
   * 
   * The supplied errors instance is used to report the validation errors.
   * 
   * @param target the collection that is to be validated
   * @param errors contextual state about the validation process
   */
  @Override
  @SuppressWarnings("rawtypes")
  public void validate(Object target, Errors errors) {
    Collection collection = (Collection) target;
    for (Object object : collection) {
      ValidationUtils.invokeValidator(validator, object, errors);
    }
  }
}

ControllerAdvice:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * Controller advice that adds the {@link CollectionValidator} to the 
 * {@link WebDataBinder}.
 * 
 * @author DISID CORPORATION S.L. (www.disid.com)
 */
@ControllerAdvice
public class ValidatorAdvice {

  @Autowired
  protected LocalValidatorFactoryBean validator;


  /**
   * Adds the {@link CollectionValidator} to the supplied 
   * {@link WebDataBinder}
   * 
   * @param binder web data binder.
   */
  @InitBinder
  public void initBinder(WebDataBinder binder) {
    binder.addValidators(new CollectionValidator(validator));
  }
}
like image 74
eruiz Avatar answered Nov 03 '22 00:11

eruiz


As you might have guessed this cannot be achieved using Spring Validation. Spring Validation implements Bean Validation(JSR 303/349) as opposed to Object validation. Unfortunately a collection is not a Java Bean. You have two options

  • Wrap your list inside a Java Bean
  • Call the validator manually in your bulk create method myEntityValidator. validate(targetObject, errors).
like image 22
Akhil Avatar answered Nov 02 '22 23:11

Akhil