|
|
spring 3 mvc help with multiple forms on one page
Hi, I am new to spring 3 mvc using annotations. Have a jsp view page with 2 forms one for login and the other for registration. I have two Controller classes for login and registration respectively. In order to view the JSP page with empty form for login, login controller has to instantiate both the loginForm model attribute and registrationForm model attribute. Same thing for Registration controller. It has to create a new instance of LoginForm just to show the JSP page.
with Spring, if we want to share 2 forms in one jsp, why does the view dictate terms to controllers ( create new empty form instances and add them to model). why doesn't the spring lt;form:form tag work if there is no model attribute is present in the ModelAndView object that matches the tag's modelattribute value? I would expect the tag just to show empty values because there is no model attribute present related to the form.
Why is there a necesssity to have an empty form object instance in model to show an empty form?
Is there a workaround for this? right now, in the methods with requestmapping.GET in both controllers, i am instantiating both loginform and registration form objects while going to show a jsp page with two empty forms. It seems like a bad choice that the controllers have to be aware of other forms that are not related to their processing just because the forms share a view page.
In spring 2.5 when SimpleFormController class was available, it used to create the new instance of form object behind the scenes before going to the formView page, so at least hiding it from developers who are extending it. Now, with annotations, each class has to instantiate the form object themselves.
Really appreciate your help!
Currently the form tag isn't able to create an empty model by itself but there is alread a JIRA entry for that issue: browse/SPR-5867 (vote for it!)
But you can inherit methods annotated with @ModelAttribute as well, so you could introduce a base class 'ControllerWithLoginAndRegistration' and create the two model beans in that base class.
After all, Spring-MVC + JSP is not a component framework but request based, so you should better think of a one to one mapping between the view and the controller. Using kind of a hack you could fake such component behaviour by creating the model bean in the tag itself: suppose you have a tag file 'login.tag' add the following at the beginning of the tag:
Code:
lt;% LoginModel lm = (LoginModel) jspContext.findAttribute(LoginModel.KEY); if (lm == null) { lm = new LoginModel(); jspContext.setAttribute(LoginModel.KEY, lm, PageContext.REQUEST_SCOPE);// spring's from tag uses request scope }
%gt;
...
lt;form:form modelAttribute=quot;%=LoginModel.KEY%gt;quot;
...Thanks Robin. Good to know that this will be resolved in spring 3.1. |
|