如何在Spring MVC中将复选框值传递给控制器
我有一个带有功能列表的jsp页面。在控制器中,我从数据库中获取此列表,并将其传递给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页面中,我使用此功能列表创建表
<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。
我的功能实体如下
public class Function {    private Integer id;
    private String name;
    private Boolean action;
...
}
我想按“保存”按钮并进入控制器“ / functionlist / save”复选框值列表。
回答:
尝试这样添加form到您的jsp页面
  <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中,您应该有一个像这样的方法
  @RequestMapping(value = { "/functionlist/save" }, method = RequestMethod.POST)    public String savePerson(@ModelAttribute("functionList")List<Function> functionList) {
        // process your 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);
    }
}
在控制器中而不是通过列表,通过包装器
  FunctionListWrapper functionListWrapper=new FunctionListWrapper();        functionListWrapper.setFunctionList(userService.getFunctionList());
        mv.addObject("functionListWrapper", functionListWrapper);
以上是 如何在Spring MVC中将复选框值传递给控制器 的全部内容, 来源链接: utcz.com/qa/416212.html








