【问题标题】:Spring MVC+JSP, get selected value from dropdown menuSpring MVC+JSP,从下拉菜单中获取选定值
【发布时间】:2013-07-16 14:46:41
【问题描述】:

我有这个页面:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我对form标签不熟悉,用这个可以吗?

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

      也许你的表单结束标签应该在 form:select 结束标签下。

      【讨论】:

      • 感谢您的回答。这对我不起作用,但你给了我一个很好的提示。
      猜你喜欢
      • 2020-04-20
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多