0

给定以下内容,如何绑定以下引导列表选择器?我从控制器传递到 index.jsp 的视图模型中填充了选择列表。但是,绑定似乎有很多变化。

class viewModel {
  List<String> theList;      // <- populated in my GET controller code
  String selectedListItem;   // <- trying to figure out how to get selected list item?
  o o o
  // assume get/set
}

index.jsp:

(我在提交按钮单击时得到了回发,我可以访问视图模型,但只需要弄清楚如何从列表中获取所选项目。)

    <form class="form-horizontal" action="myController/indexSubmit" method="post">
        <select class="form-control" placeholder=".input-medium" height>
            <c:forEach items="${viewModel.gettheList()}" var="item" varStatus="count"> 
                <option value="${count.index}">${item }</option>
            </c:forEach>
        </select>   
        <button type="submit" class="btn btn-primary btn-medium">Submit</button>   
    </form> 

控制器:

@RequestMapping(value="indexSubmit", method = RequestMethod.POST)
public String indexSubmit(@ModelAttribute("viewModel") viewModel viewModel, ModelMap model) {
    String item = viewModel.getselectedListItem(); // <- How can I pass this in?
    System.out.println("Selected Item: " + item);
    return "myController/index";  // <- want to add as query param: ?item=theItem  
}   
4

1 回答 1

2

您不需要创建特殊类来绑定元素列表。将选择与控制器绑定的最简单示例:

控制器:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpServletRequest request, Model model) {  
    List<String> listString = new ArrayList<String>();
    listString.add("hello");
    listString.add("world");
    listString.add("from");
    listString.add("Belarus");
    model.addAttribute("listString", listString);
    return "index";
}

@RequestMapping(value = "test", method = RequestMethod.POST)
public String test(@RequestParam String selectedString, Model model) {
    System.out.println(selectedString);
    return "index";
}

index.jsp:

<form class="form-horizontal" action="${home}/test" method="post">
    <select name="listString" class="form-control">
        <c:forEach items="${listString}" var="item" varStatus="count"> 
            <option value="${count.index}">${item}</option>
        </c:forEach>
    </select>   
    <button type="submit" class="btn btn-primary btn-medium">Submit</button>   
</form> 

提交表单后使用该代码,您将在控制台中看到选定的项目索引。

如果您还想传输初始列表(listItem),您可以再次选择所有项目并选择属性multiple="multiple"并将其样式设置为显示:无;在此之后声明另一个参数@RequestParam List<String> listString,您将获得初始字符串数组。

关于添加参数:

return "myController/index";  // <- want to add as query param: ?item=theItem  

你不能那样传递参数。那是因为您返回视图的名称(简单的 jsp 名称的图块),而不是 url。如果您想使用参数访问 url,您可以:

return "forward:/index?item=theItem";

希望能帮助到你

于 2013-08-20T21:06:32.720 回答