gpt4 book ai didi

spring - 如何在 Spring MVC 中将复选框值传递给 Controller

转载 作者:行者123 更新时间:2023-12-02 21:11:34 24 4
gpt4 key购买 nike

我有一个包含函数列表的 jsp 页面。在 Controller 中,我从数据库获取此列表并将其传递给 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;
...
}

我想按“保存”按钮并进入 Controller “/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);
}
}

在 Controller 中传递包装器而不是传递列表

  FunctionListWrapper functionListWrapper=new FunctionListWrapper();
functionListWrapper.setFunctionList(userService.getFunctionList());
mv.addObject("functionListWrapper", functionListWrapper);

有关更多详细信息,请查看以下问题:question 1question 2

关于spring - 如何在 Spring MVC 中将复选框值传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com