如何在Spring MVC中将复选框值传递给控制器 [英] How to pass checkbox values to the controller in Spring MVC
问题描述
我有一个包含功能列表的jsp页面.在控制器中,我从数据库中获取此列表,并将其传递给jsp.
I have a jsp page with list of functions. Here in controller I get this list from database and pass it to jsp.
@RequestMapping(value = "/functionlist", method = RequestMethod.GET)
public ModelAndView functionList(Model model) throws Exception {
ModelAndView mv = new ModelAndView("functionList");
mv.addObject("functionList", getFunctionsFromDB());
return mv;
}
在我的jsp页面中,我使用此功能列表创建表
In my jsp page I create table using this list of functions
<table id="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty functionList}">
<c:forEach var="function" items="${functionList}">
<tr>
<td><input name="id" value="${function.id}" hidden></td>
<td>${function.name}</td>
<td>
<input type="checkbox" id="${function.id}" value="${function.action}"></td>
</tr>
</c:forEach>
</c:when>
</c:choose>
</tbody>
</table>
<button type="submit" name="save">Save</button>
我还将功能ID赋予复选框ID.
I also give function id to checkbox id.
我的Function实体如下
My Function entity is the following
public class Function {
private Integer id;
private String name;
private Boolean action;
...
}
我想按保存"按钮并进入控制器"/functionlist/save"我的复选框值列表.
I want to press button Save and get in controller "/functionlist/save" my list of checkbox values.
推荐答案
尝试将这样的form
添加到您的jsp页面
Try to add form
like this to your jsp page
<form:form id="yourForm" action="/functionlist/save" method="POST" modelAttribute="functionList">
<c:forEach items="${functionList}" varStatus="status" var="function">
<tr>
<td>${function.name}</td>
<td>
<form:checkbox path="functionList[${status.index}].action"/>
</td>
</tr>
</c:forEach>
<input type="submit" value="submit" />
</form:form>
在Controller中,您应该有这样的方法
and in Controller you should have a method like this
@RequestMapping(value = { "/functionlist/save" }, method = RequestMethod.POST)
public String savePerson(@ModelAttribute("functionList")List<Function> functionList) {
// process your list
}
如果这不起作用,则可以尝试包装列表.
If this does not work, you can try to wrap you list.
public class FunctionListWrapper {
private List<Function> functionList;
public FunctionListWrapper() {
this.functionList = new ArrayList<Function>();
}
public List<Function> getFunctionList() {
return functionList;
}
public void setFunctionList(List<Function> functionList) {
this.functionList = functionList;
}
public void add(Function function) {
this.functionList.add(function);
}
}
在控制器中,而不是通过列表,而是通过包装器
in controller instead of passing list, pass wrapper
FunctionListWrapper functionListWrapper=new FunctionListWrapper();
functionListWrapper.setFunctionList(userService.getFunctionList());
mv.addObject("functionListWrapper", functionListWrapper);
有关更多详细信息,请查看以下问题:问题2
For more details please take a look at this questions: question 1 and question 2
这篇关于如何在Spring MVC中将复选框值传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!