5

Is there a way to validate request parameter with spring without checking it in every function? For example, every method in a controller produces list of elements and each method accept 'from' and 'to' parameters, so the validation is: from >=0 && to > 0 && from < to

I want to configure spring to return BAD_REQUEST or some other status just like it does when it cannot convert string to int parameter.

Thanks.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Dima
  • 1,774
  • 5
  • 21
  • 31

2 Answers2

1

If you use form-backing objects using @RequestBody, then you can use JSR-303 bean validation, where you annotate your form bean. See http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#validation-beanvalidation for full details. Then you don't need to bother with Validator objects or other coding - you just annotate.

atrain
  • 9,139
  • 1
  • 36
  • 40
  • Unfortunately it's not a form. – Dima Sep 15 '11 at 13:16
  • If its not a client-side HTML `
    `, that doesn't matter; Spring on the server doesn't know anything about HTML forms. It will still automatically map name-value pairs from the request to a Command object configured via `@RequestBody`.
    – atrain Sep 15 '11 at 13:19
  • Here's a question that has a full JSR-303 validator implementation in the accepted answer. You can modify it to suit your case. http://stackoverflow.com/questions/1972933/cross-field-validation-with-hibernate-validator-jsr-303 – digitaljoel Sep 15 '11 at 14:49
0

Directly - no. But if you wrap them in a class, you can have a Validator that .supports(YourClass.class) and validate(..) it.

public class Range {
   private int from;
   private int to;
   //setters & getters
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I'm not sure how to wrap parameters of request mapping such as /users?from=1&to=20. – Dima Sep 15 '11 at 13:17