Confused as to how to validate spring mvc form, what are my options?
- by Blankman
Latest spring mvc, using freemarker.
Hoping someone could tell me what my options are in terms of validating a form with spring mvc, and what the recommend way would be to do this.
I have a form that doesn't map directly to a model, it has input fields that when posted, will be used to initialze 2 model objects which I will then need to validate, and if they pass I will save them.
If they fail, I want to return back to the form, pre-fill the values with what the user entered and display the error messages.
I have read here and there about 2 methods, once of which I have done and understand how it works:
@RequestMapping(...., method = RequestMethod.POST)
public ModelAndView myMethod(@Valid MyModel, BindingResult bindingResult) {
ModelAndView mav = new ModelAndView("some/view");
mav.addObject("mymodel", myModel);
if(bindingResult.hasErrors()) {
return mav;
}
}
Now this worked if my form mapped directly to the form, but in my situation I have:
form fields that don't map to any specific model, they have a few properties from 2 models.
before validation occurrs, I need to create the 2 models manually, set the values from the values from the form, and manually set some properties also:
Call validate on both models (model1, model2), and append these error messages to the errors collection which I need to pass back to the same view page if things don't work.
when the form posts, I have to do some database calls, and based on those results may need to add additional messages to the errors collection
Can someone tell me how to do this sort of validation?
Pseudo code below:
Model1 model1 = new Model1();
Model2 model2 = new Model2();
// manually or somehow automatically set the posted form values to model1 and model2.
// set some fields manually, not from posted form
model1.setProperty10(GlobalSettings.getDefaultProperty10());
model2.setProperty11(GlobalSettings.getDefaultProperty11());
// db calls, if they fail, add to errors collection
if(bindingResult.hasErrors()) {
return mav;
}
// validation passed, save
Model1Service.save(model1);
Model2Service.save(model2);
redirect to another view
Update
I have using the JSR 303 annotations on my models right now, and it would great if I can use those still.
Update II
Please read the bounty description below for a summary of what I am looking for.