从 spring 中的 HTML 表单获取复选框值作为数组

Get checkbox values as array from HTML form in spring

我有一个表格可以显示列表中的所有项目。每个元素旁边都有一个复选框:

<input type="checkbox" name="selected" value="${product.id}">

单击“继续”按钮后,我进入了一个控制器,我想在其中列出所有选中的复选框。我试着这样做:

@GetMapping
    public String getOrderForm(Model model, @RequestParam(value = "selected") String[] selected){

但是我得到的错误是没有这样的对象。我怎样才能得到这个复选框列表?

控制器将接受选中的复选框作为逗号分隔的字符串。

@GetMapping
public String getOrderForm(Model model, @RequestParam("selected") String selected){
    String[] stringArray = selected.split(",");
    List<String> list = Arrays.asList(stringArray);

    ... <your code>

    return "somePage";
}

chandra kant 说的是对的,但是您还需要知道一件事才能使这项工作成功。您必须保持每个复选框的名称相同,然后才能起作用。它会自动生成一个以逗号分隔的字符串。您可以通过仅在控制器中打印它来测试它,您也可以在 URL.

中看到它
 @GetMapping
 public String getOrderForm(@Param("selected") String selected){
  System.out.println(selected);//just to check whether we are getting comma separated value or not
  String[] selectedArray = selected.split(",");
  List<String> list = Arrays.asList(stringArray);
}

将选中的复选框值作为字符串数组接收到控制器中。您必须为复选框组指定相同的所有复选框的名称 属性 的值。然后您将在控制器中收到所选复选框值作为数组。

对于同一组复选框,一组复选框的名称属性的特定相同值:

<input type="checkbox" name="selected" value="${product1.id}">
<input type="checkbox" name="selected" value="${product2.id}">
<input type="checkbox" name="selected" value="${product3.id}">

在控制器中:

@GetMapping
    public String getOrderForm(Model model, @RequestParam(value = "selected") String[] selected){

这对我有用

 @GetMapping
 public String getOrderForm(Model model, @RequestParam("selected") String selected){
  System.out.println(selected);//just to check whether we are getting comma separated value or not
  String[] selectedArray = selected.split(",");
  List<String> list = Arrays.asList(stringArray);
}

在html表格中需要添加:

<input type="checkbox" name="selected" th:value="${product.id}">

我的控制器现在看起来像这样:

 @GetMapping
    public String getOrderForm(Model model, @RequestParam(value = "selected", required = false)Integer[] selected){

如果没有选中复选框,则选中的将为空