2

I can have Spring convert my json POST submission into an object with a method like this:

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public ResponseEntity<String> doSomething(@RequestBody SomeUsefulPojo usefulPojo) {
       // use the useful pojo, very nice
    }

I can get JSR-303 validation by setting up all the application context magic, and by creating my post method as such and submitting with form-encoded values:

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public ResponseEntity<String> doSomething(@Valid SomeUsefulPojo validPojo) {

       // use validPojo, I'm happy
}

Problem is, the second one appears to want to use a form-encoded approach, whereas I want the JSON handed in. Any way to get the best of both worlds - validation AND json POST? I've tried @Valid and @RequestBody together, but it doesn't invoke the validation that way.

Ideas?

Dave LeBlanc
  • 346
  • 4
  • 12
  • The bug is apparently fixed in v3.1 M2 [Linked Solution][1] [1]: http://stackoverflow.com/a/7811192/41223 – tzrlk Aug 20 '12 at 01:15

1 Answers1

1

Use the first approach, and validate the param manually.

import javax.validation.Validator; ...

@Resource
Validator validator;

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public ResponseEntity<String> doSomething(@RequestBody SomeUsefulPojo usefulPojo) {
    Set<ConstraintViolation<?>> cvs = validator.validate(usefulPojo);
    if (!cvs.isEmpty()) throw new ConstraintViolationException(cvs);
    ...
}

If you need to bind the errors to your BindResult, you could try the approach here:

http://digitaljoel.nerd-herders.com/2010/12/28/spring-mvc-and-jsr-303-validation-groups/

More ideas here:

http://blog.jteam.nl/2009/08/04/bean-validation-integrating-jsr-303-with-spring/

Peter Davis
  • 761
  • 7
  • 13
  • Ok, that's the approach I was taking - glad to see I'm on the right track. – Dave LeBlanc Jun 13 '11 at 03:18
  • It does seem like a Spring bug that it didn't work for you the first time. I don't use JSON, but I do follow this manual validation pattern for other reasons like JSR-303's lack of support for groups on @Valid. – Peter Davis Jun 17 '11 at 23:24