2

I want to validate the request parameter which is just a string value. Most of the examples on the net talks about validating a domain object with custom validator. But I want to write a validator just for String value. How to achieve that?

@Controller @RequestMapping("/base") class MyController{ //value needs to be validated. @RequestMapping("/sub") public String someMethod(@RequestParam String value, BindingResult result){ if(result.hasErrors()){ return "error"; } //do operation return "view"; } } 

I want to use the Validator interface that is already available in Spring, not AOP or any IF conditions

3
  • You could use AOP and intercept the method call, validate the parameter and if it's not valid modify manually the binding result or throw an exception and handle it in the controller. Commented Apr 17, 2015 at 9:15
  • I don't think I need AOP here. I want to use the Validator interface that is already available in Spring Commented Apr 17, 2015 at 9:55
  • How about creating a wrapper object over the String, and add JSR 303 annotations for validation, or creating a validator for the respective object? Commented Apr 17, 2015 at 10:26

2 Answers 2

2

Your controller cannot validate the param, because BindingResult shall follow a ModelAttribute, not a RequestParam.

So if you want to use the Spring MVC automatic validation, you should use a class containing your string as a ModelAttribute :

class MyController { @RequestMapping("/sub") public String someMethod(@ModelAttribute Params params, BindingResult result){ if(result.hasErrors()){ return "error"; } //do operation with params.value return "view"; } public static class Params { // add eventual JSR-303 annotations here String value; // getter and setter ommited for brievety } } 

Of course, this assumes you put a validator into the WebBinder for example through an @InitBinder annotated method of your controller.

Sign up to request clarification or add additional context in comments.

Comments

0
 //value needs to be validated. @RequestMapping("/sub") public String someMethod(@RequestParam String value, BindingResult result) throws SomeException { if (!ValidationUtils.isValid(value)) { throw new SomeException("Some text"); } 

1 Comment

Could you please elaborate more your answer adding a little more description about the solution you provide?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.