Reputation: 15254
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
Upvotes: 2
Views: 2652
Reputation: 149165
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.
Upvotes: 2
Reputation: 1
//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");
}
Upvotes: 0