开发者

Getting JSR-303 validation with JSON posted object?

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?


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜