Marouen Marouen - 1 month ago 5
Java Question

How to retrieve a value from Combobox and assign it to an Entity using springMVC and JSP

i would like to retrieve a value from combobox in jsp

<form:select />
which get its values from another Entity named Group, and assign it to a User. both of Entities are mapped together with
@OneToMany
and
@ManyToOne
. so many users can be assigned to one Group.
PS: the combobox Content is dynamic.

here is my Controller file:

@RequestMapping(value = "/user/add")
public ModelAndView addUserPage() {
ModelAndView mav = new ModelAndView("/admin/user/addUser");
List<Group> groups = groupService.listGroups();
List<String> groupNames = new ArrayList<String>();

for (Group m : groups) {
groupNames.add(m.getGroupName());
}
mav.addObject("user", new User());
mav.addObject("groupNames", groupNames);
return mav;
}

@RequestMapping(value = "/user/add/process")
public ModelAndView addingUser(@ModelAttribute(value = "user") User user,
@ModelAttribute(value = "groupName") String groupName) {

ModelAndView mav = new ModelAndView("redirect:/spring/user/list.html");
user.setDateModification(new Date());
Group group = groupService.getGroupByGroupName(groupName);
user.setGroup(group);
userService.addUser(user);
String message = "User was successfully added.";
mav.addObject("message", message);

return mav;
}


and my JSP file:

<form:form method="POST" commandName="user"
action="/myApplication/spring/user/add/process.html">
<label>username</label>
<form:input path="username" class="span12"></form:input>
<label>Password</label>
<form:input path="password" type="password" class="span12"></form:input>
<label>Groupe</label>
<form:select path="group">
<form:option value="NONE" label="--- Choisir un groupe ---" />
<form:options items="${groupNames}" />
</form:select>
<label>Code Banque</label>
<form:input path="codeBanque" class="span12"></form:input>
<label>Code Agence</label>
<form:input path="codeAgence" class="span12"></form:input>
<input value="Ajouter" type="submit"
class="btn btn-primary pull-right">
<div class="clearfix"></div>
</form:form>


My goal is to assign the User to a Group threw the form of adding users. i was able to get one ModelAttribure which is user, but i can't get Two !

thanks

Answer

i fixed my problem and here is the solution:

UserController:

    @RequestMapping(value = "/user/add")
public ModelAndView addUserPage() {
    ModelAndView mav = new ModelAndView("/admin/user/addUser");
    List<Group> groups = groupService.listGroups();
    mav.addObject("groups", groups);
    mav.addObject("user", new User());
    return mav;
}

and my Jsp page:

                        <label>Groupe</label>
                        <form:select path="group.idGroup" items="${groups}"
                            itemValue="idGroup" itemLabel="groupName" multiple="false"
                            class="span12">
                        </form:select>