Spring MVC Multiple ModelAttribute On the Same Form

I don’t think so if you can bind multiple models using the Spring form. In fact you should take a look in the spring binding form.
http://static.springsource.org/spring/docs/1.1.5/taglib/tag/BindTag.html
Take a look in the sample code. I have not tested the code. Let know in case of any issues.

Model

public class User{

private String username;
private String password;

..Setter and Getters
}

public class UserProfile{
private String firstName;
private String lastName;

setter and getter
}

Controller

@Controller
public class MyController{
    @RequestMapping(....)
    public String newAccountForm(ModelMap map){
        User user = new User(); //Would recommend using spring container to create objects
        UserProfile profile = new UserProfile();

        map.addAttribute('user', user);
        map.addAttribute('profile', profile);

        return "form"
    }




     @RequestMapping(....)
        public String newAccountForm(@ModelAttrbite('User')User user, BindingResult resultUser, @ModelAttribute('UserProfile')UserProfile userProfile, BindingResult resultProfile){

//Check the binding result for each model. If not valid return the form page again
//Further processing as required.

        }
    }

JSP

<%@taglib  uri="http://www.springframework.org/tags" prefix="spring">

<form action="" method="post">

<spring:bind path="user.username">
   <input type="text" name="${status.expression}" value="${status.value}"><br />
        </spring:bind>

<spring:bind path="user.password">
   <input type="password" name="${status.expression}" value="${status.value}"><br />
        </spring:bind>

<spring:bind path="profile.firstName">
   <input type="text" name="${status.expression}" value="${status.value}"><br />
        </spring:bind>
<spring:bind path="profile.lastName">
   <input type="text" name="${status.expression}" value="${status.value}"><br />
        </spring:bind>

<input type="submit" value="Create"/>
</form>

Leave a Comment