I’m trying to get my feet wet with Spring MVC 3.0, and while I can get it to work, I can’t seem to handle this particular scenario efficiently.
I have a controller with that handles “/{studyName}/module” prefix, and it looks something like this:-
@Controller
@RequestMapping(value = "/{studyName}/module")
public class ModuleController {
@RequestMapping(...)
public ModelAndView getA(@PathVariable String studyName, ...) {
if (!validStudy(studyName)) { return bad request; }
...
}
@RequestMapping(...)
public ModelAndView getB(@PathVariable String studyName, ...) {
if (!validStudy(studyName)) { return bad request; }
...
}
@RequestMapping(...)
public ModelAndView getC(@PathVariable String studyName, ...) {
if (!validStudy(studyName)) { return bad request; }
...
}
@RequestMapping(...)
public ModelAndView getD(@PathVariable String studyName, ...) {
if (!validStudy(studyName)) { return bad request; }
...
}
}
The problem with this code is, I have the studyName validation scattered all over the methods and possibly in other Controllers’ methods too. Is there a way I can perform validation on studyName path variable all in one spot without using something like AOP? How do you handle validation like this?
Thanks.
Right now, it’s a little tricky to make this happen automatically, but it is possible. You should use a Bean validation (JSR-303) provider that implements appendix C. Currently that’s Apache BeanValidation or Hibernate Validator 4.2 (which is in beta).
Add your chosen bean validation implementation to the classpath. This will be the implementation of JSR-303 that Spring MVC uses.
Second, annotate the method parameter with @Valid and any constraint annotations, like @NonNull.
This will look something like:
That should work. You’d then need to check your Spring errors for any problems.
Alternatively, if you don’t make use of any other Spring parameters, you can register a validator with an InitBinder like so: