I'm running a webapp in Spring Web MVC 3.0 and I have a number of controller methods whose signatures are roughly as follows:
@RequestMapping(value = "/{level1}/{level2}/foo", method = RequestMethod.POST)
public ModelAndView createFoo(@PathVariable long level1,
@PathVariable long level2,
@RequestParam("foo_name") String fooname,
@RequestParam(value = "description", required = false) String description);
I'd like to add some validation - for example, description
should be limited to a certain length or fooname
should only contain certain characters. If this validation fails, I want to return a message to the user rather than just throw some unchecked exception (which would happen anyway if I let the data percolate down to the DAO layer). I'm aware of JSR303 but have not worked with it and don't quite understand how to apply it in a Spring context.
From what I understand, another option would be to bind the @RequestBody
to an entire domain object and add validation constraints there, but currently my code is set up to accept individual parameters as shown above.
What is the most straightforward way to apply validation to input parameters using this approach?
There's nothing built in to do that, not yet anyway. With the current release versions you will still need to use the WebDataBinder to bind your parameters onto an object if you want automagic validation. It's worth learning to do if you're using SpringMVC, even if it's not your first choice for this task.
It looks something like this:
If you have Hibernate Validator 4 or later on your classpath and use the default dispatcher setup it should "Just work."
Editing since the comments were getting kind of large:
Any Object that's in your method signature that's not one of the 'expected' ones Spring knows how to inject, such as
HttpRequest
,ModelMap
, etc, will get data bound. This is accomplished for simple cases just by matching the request param names against bean property names and calling setters. The@ModelAttribute
there is just a personal style thing, in this case it isn't doing anything. The JSR-303 integration with the @Valid on a method parameter wires in through theWebDataBinder
. If you use@RequestBody
, you're using an object marshaller based on the content type spring determines for the request body (usually just from the http header.) The dispatcher servlet (AnnotationMethodHandlerAdapter
really) doesn't have a way to 'flip the validation switch' for any arbitrary marshaller. It just passes the web request content along to the message converter and gets back a Object. No BindingResult object is generated, so there's nowhere to set the Errors anyway.You can still just inject your validator into the controller and run it on the object you get, it just doesn't have the magic integration with the
@Valid
on the request parameter populating theBindingResult
for you.This seems to be possible now (tried with Spring 4.1.2), see https://raymondhlee.wordpress.com/2015/08/29/validating-spring-mvc-request-mapping-method-parameters/
Extract from above page:
Add MethodValidationPostProcessor to Spring @Configuration class:
Add @Validated to controller class
Use @Size just before @RequestParam
}
Handle ConstraintViolationException in an @ExceptionHandler method
If you have multiple request parameters that need to be validated (with Http GET or POST). You might as well create a custom model class and use @Valid along with @ModelAttribute to validate the parameters. This way you can use Hibernate Validator or javax.validator api to validate the params. It goes something like this:
Request Method:
ModelRequest class:
Hope that helps.