1

这是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>

这是控制器的相关部分:

@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;
}

如果我执行上面的代码,那么当我提交表单时将创建一个全新的用户对象。但是,当我单击“提交”时,我想获得一个 ALREADY EXISTING User instance,这些实例明确存在于此处:

<c:forEach items="${USERS}" var="user">
    <form:option value="${user.userName}"></form:option>

如何修改我的代码以获取现有对象?
实际上,我知道一种获取现有实例的丑陋方法。通过提交表单,我可以创建一个新的用户实例,其用户名与我正在寻找的用户名相同。然后在 DaoImpl 类中,我可以查询与新创建的用户共享用户名的“旧”用户。但我想这是相当浪费和丑陋的,所以我不敢相信没有更好的方法。

更新

   <!-- 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;

            }
4

1 回答 1

0
  @ModelAttribute
    public void fillUsers(Model model) {
        model.addAttribute("USERS", userService.getUsers());
    }

    @ModelAttribute
    public void getUser(@RequestParam(required = false) String userName, Model model) {
        User user = null;
        if (userName != null) {
            user = userService.getUserByName(userName);
        }
        if (user == null) {
            user = new User();
        }
        model.addAttribute("user", user);
    }

    @RequestMapping("/toAddFriend")
    public String toAddNewFriend() {
        return "addFriend";

    }

    @RequestMapping(value = "/requestForFriends", method = RequestMethod.POST)
    public String requestNewFriend(@ModelAttribute("user") User user) {
        System.out.println(user.getUserName());
        System.out.println(user.getEmail());
        return "addFriend";

    }
于 2012-08-23T06:31:25.893 回答