here is the jsp:
<c:if test="${!empty USERS}">
<form:form method="post" action="requestForFriends.html" commandName="user">
<form:select path="userName">
<c:forEach items="${USERS}" var="user">
<form:option value="${user.userName}"></form:option>
</c:forEach>
</form:select>
<input type="submit" value="Send freindship request" />
</form:form>
</c:if>
here is the controller’s relevant part:
@RequestMapping("/toAddFriend")
public ModelAndView toAddNewFriend() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("USERS", userService.getUsers());
ModelAndView ret=new ModelAndView("addFriend", model);
ret.addObject("user", new User());
return ret;
}
if I do the code above then a brand new User object will be created when I submit the form. But when I click “submit” I would like to get one of the ALREADY EXISTING User instance, which are clearly present in here:
<c:forEach items="${USERS}" var="user">
<form:option value="${user.userName}"></form:option>
How can I modify my code to get the existing object?
Actually I know an ugly way to get the existing instance. By submitting the form I can create a new User instance with the same username as the one has that I am looking for. Then in the DaoImpl class I can query for the “old” User which shares the userName with the newly created one. But I guess it is quite wasteful and ugly so I can’t believe that there is no better way.
UPDATE
<!-- language: lang-java -->
@RequestMapping(value = "/requestForFriends", method = RequestMethod.POST)
public ModelAndView requestNewFriend(@ModelAttribute("user") User user, BindingResult result) {
System.out.println(user.getUserName());
System.out.println(user.getEmail());
Map<String, Object> model = new HashMap<String, Object>();
model.put("USERS", userService.getUsers());
ModelAndView ret=new ModelAndView("addFriend", model);
ret.addObject("user", new User());
return ret;
}
1 Answer