I've got a question concerning Spring forms (with Thymeleaf, to be specific).
I know that I can use only one bean at a time to back a form in Spring, so I thought it would be nice to let the Controller select which bean should be bound to the form,depending on which parameters are sent. But instead of writing a new RequestMapping for every new param, I wondered if I could somehow map the params only to the ModelAttribute
itself.
I thought of something like this:
@Controller
public class FormController{
@ModelAttribute("bean", params={"type=bean1"}) //this declaration is invalid
public IBean loadEmptyModelBean(){
return new Bean1();
}
@ModelAttribute("bean", params={"type=bean2"})
public IBean loadEmptyModelBean(){
return new Bean2();
}
//..
@RequestMapping(method=RequestMethod.GET)
public String showForm(IBean bean){
//..
}
@RequestMapping(method=RequestMethod.POST, params={"validate"})
public String validate(@Valid IBean bean, BindingResult result){
List<ObjectError> errors = bean.validate();
for(ObjectError e: errors){
result.addError(e);
}
//redirecting, etc
}
}
As you can see, I would instantiate different Beans according to the params and still be using only one method for each GET and POST procedure, because IBean would be an interface that forces all Beans to implement a validate()-method.
I started with Spring only a few days ago, and was wondering if somebody knows a solution to this, who's more experienced than me : )
I searched for an answer but couldn't find a solution to my specific problem. I guess, I could implement a lot of handlers, that are filtered by params, but that would be very redundant, because every method has to do the same (call the validate()-method and add the new errors to the BindingResult)... and I don't think that would be a good solution, tbh.
Hope my question doesn't sound to foolish ^^
Thanks in advance for your time and effort.