For a simple RESTful JSON api implemented in Spring MVC, can I use Bean Validation (JSR-303) to validate the path variables passed into the handler method?
For example:
@RequestMapping(value = "/number/{customerNumber}")
@ResponseBody
public ResponseObject searchByNumber(@PathVariable("customerNumber") String customerNumber) {
...
}
Here, I need to validate the customerNumber variables's length using Bean validation. Is this possible with Spring MVC v3.x.x? If not, what's the best approach for this type of validations?
Thanks.
Spring does not support
@javax.validation.Valid
on@PathVariable
annotated parameters in handler methods. There was an Improvement request, but it is still unresolved.Your best bet is to just do your custom validation in the handler method body or consider using
org.springframework.validation.annotation.Validated
as suggested in other answers.@PathVariable
is not meant to be validated in order to send back a readable message to the user. As principle a pathVariable should never be invalid. If a pathVariable is invalid the reason can be:@Valid
is needed and no message is needed, just fix the code;@Valid
is needed, no meaningful message to the user should be given.In both cases just leave an exception bubble up until it is catched by the usual Spring ExceptionHandlers in order to generate a nice error page or a meaningful json response indicating the error. In order to get this result you can do some validation using custom editors.
Create a
CustomerNumber
class, possibly as immutable (implementing aCharSequence
is not needed but allows you to use it basically as if it were aString
)Create an editor implementing your validation logic (in this case no whitespaces and fixed length, just as an example)
Register the editor in the Controller
Change the signature of your controller method accepting
CustomerNumber
instead ofString
(whatever yourResponseObject
is ...)The solution is simple:
And yes, PathVariables are ment to be validated, like any user input.
Instead of using @PathVariable, you can take advantage of Spring MVC ability to map path variables into a bean:
And the bean contains the actual validation rules:
Make sure that your path variables (
{id}
) correspond to the bean fields (id
);Path variable may not be linked with any bean in your system. What do you want to annotate with JSR-303 annotations? To validate path variable you should use this approach Problem validating @PathVariable url on spring 3 mvc
You can use like this: use
org.springframework.validation.annotation.Validated
to validRequestParam
orPathVariable
.step.1 init
ValidationConfig
step.2 Add
@Validated
to your controller handler class, Like:step.3 Add
validators
to your handler method:final step. Add exception resolver to your context: