我正在构建我的第一个 Spring MVC 应用程序,但我遇到了一些困难。我调用数据库来检索数字(区域)列表,然后将它们填充到列表框中。用户应该选择其中一项,然后点击提交按钮。问题是我不知道如何在 Controller 端捕获它。起初我以为这就像获取参数一样简单,但我想并非如此。我不想仅仅为了一个数字而构建一个Java类/Bean。这看起来有点愚蠢。那么让我与您分享我的代码。
JSP:
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Branches</h2>
<form:form method="get" action="branch.html">
<table>
<c:if test="${not empty lists}">
<select name="regions" size="4">
<c:forEach var="listVal" items="${lists}">
<option>${listVal} </option>
</c:forEach>
</select>
</c:if>
</table>
</form:form>
<form:form method="get" action="loadbranches.html">
<c:if test="${not empty lists}">
<select name="branches" size="4">
<c:forEach var="branchVal" items="${branches}">
<option>${branchVal} </option>
</c:forEach>
</select>
</c:if>
<tr>
<td colspan="2">
<input type="submit" value="submit choice" />
</td>
</tr>
</form:form>
</body>
</html>
Controller :
@Controller
@SessionAttributes
public class BranchController {
@RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches()
{
//org.springframework.web.util.WebUtils.getParametersStartingWith(, prefix)
DatabaseConnect dbCon = new DatabaseConnect();
ArrayList<Object> branches = dbCon.loadData(USER SELECTED NUMBER I CANNOT FIGURE OUT);
ModelAndView model = new ModelAndView("branch");
model.addObject("branch", branches);
return model;
}
@RequestMapping("/branch")
public ModelAndView showRegions()
{
DatabaseConnect dbCon = new DatabaseConnect();
ArrayList<Object> regionIDS = dbCon.loadData("regions");
ModelAndView model = new ModelAndView("branch");
model.addObject("lists", regionIDS);
return model;
}
}
正如您所见,应用程序实际上还没有那么复杂。我正在使用数据库和另一个 Java 类,但它工作得很好。那么有什么方法可以从请求参数或其他内容的列表框中获取用户选择吗?理想情况下,我希望在用户点击提交时发生这种情况,所以这就是为什么除了数字(区域)列表的初始加载之外还有一个单独的表单标记(如果有意义的话)。我已经查看了涉及选择路径参数的不同示例,但是在用户单击提交按钮后,是否有一种简单的方法可以从列表框中获取选择?我非常感谢您的帮助!
谢谢!
最佳答案
试试这个:
@RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches(@RequestParam(value="branches") String branches)
{
....
}
如果用户可以选择超过 1 个分支(多选),您可以注入(inject)一个列表:
@RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches(@RequestParam(value="branches") List<String> branches)
{
....
}
关于java - 在 Spring MVC/JSP/Controller 中从列表框中获取用户的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23692731/