Spring MVC + JSP,从下拉菜单中获取选定的值

时间:2013-07-16 14:46:41

标签: jsp spring-mvc drop-down-menu jsp-tags

我有这个页面:

    <form method="post" action="/monitor/admin/transferDevice/${device.deviceId}" >
        <input type="submit" value="Transfer Device">
    </form>

<form:select path="users">
    <option value="">Select</option>
    <c:forEach var="theUser" items="${users}">
        <form:option value="${theUser.userId}"><c:out value="${theUser.name} ${theUser.surname}"/></form:option>
    </c:forEach>
</form:select>

其中users是用户对象列表。

我的控制员:

@RequestMapping(value = "/admin/transferDevice/{deviceId}", method = RequestMethod.POST)
public String transferForDevice(@PathVariable("deviceId") int deviceId) throws Exception {

    //some logic here

    return "redirect:/admin";
}

所以问题看起来很简单但不适合我。当我按下按钮时,如何将所选用户传递给我的控制器方法?

2 个答案:

答案 0 :(得分:3)

我找到了解决问题的方法。所以这里是我的更新页面:

<form:form modelAttribute="selectedUser" method="POST" action="/monitor/admin/transferDevice/${device.deviceId}" style="width: 310px;">
   <input type="submit" value="Transfer Device" style="height: 68px; width: 197px; ">
        <tr>
            <td>User:</td>
            <td><form:select path="userId">
                <form:option value="0" label="--- Select ---" />
                <c:forEach var="theUser" items="${users}">
                    <form:option value="${theUser.userId.toString()}"><c:out value="${theUser.name} ${theUser.surname}"/></form:option>
                </c:forEach>
                </form:select>
            </td>
        </tr>
</form:form>

我的控制员:

@RequestMapping(value = "/admin/transferDevice/{deviceId}", method = RequestMethod.POST)
public String transferForDevice(@PathVariable("deviceId") int deviceId, @ModelAttribute("selectedUser") User user) throws Exception {
    //so now I can use "user" from @ModelAttribute
    return "redirect:/admin";

答案 1 :(得分:2)

我不熟悉表单标签,使用它可以吗?

@RequestMapping(value = "/admin/transferDevice/{deviceId}", method = RequestMethod.POST)
public String transferForDevice(@PathVariable("deviceId") int deviceId, @RequestParam("users") String user) throws Exception {

也许您的表单结束标记应该在表单下:select end tag。