我正在制作一个Spring MVC项目,而我的.jsp中有此表格
JSP
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
所以我有
User
和CafeTable
模型,但是我的模型属性是CafeTable
。使用提交按钮,我需要在控制器中同时获取两个选定的值:
@RequestMapping(value = "/admin/assign/add", params = "assign", method = RequestMethod.POST)
public String assign(@ModelAttribute("cafeTable") CafeTable cafeTable) {
//set cafeTable's UserID field matching selected fullName value
tableService.addTable(cafeTable);
return "admin";
}
我怎样才能做到这一点?
最佳答案
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<input type="hidden" value="${user.fullName}" name="fullname">
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
如果您在CafeTable中没有fullname属性,请尝试在form:form之内添加一个隐藏字段,例如
<input type="hidden" value="${user.fullName}" name="fullname">
并将可选的请求参数添加到您的控制器中,如下所示
@RequestMapping(value = "/admin/assign/add", method = RequestMethod.POST)
public String save(@RequestParam("fullname") String fullname,@Valid @ModelAttribute("cafeTable") CafeTable cafeTable) {
//now you can access full name from fullname variable here
....
}
我尚未测试此代码。