首页 > 解决方案 > 使用 Spring + Thymeleaf 从表中的选定复选框中获取 Id

问题描述

我收到一个错误 NotReadablePropertyException: Invalid property 'userIds' of bean class [...ListOfIds]... 我不知道为什么。如果我删除th:field复选框上的属性,表格会正确填写。我已经尝试过th:field="*{requestIds}"th:field="*{requestIds.ids}" 我正在尝试做的是从选定的复选框中收集 id 列表并将它们传递回控制器以进行发布。

形式

public class ListOfIds {
   List<Long> ids = new ArrayList<>();

   public List<Long> getIds() { return ids; }
// I've tried both set methods by themselves and together.
   public void setIds(List<Long> ids) { this.ids = ids; }
   public void setIds(Long[] ids) { this.ids = Arrays.asList(ids); }
}

请求 bean

public class Request {
   long id;
   String name;
   String phone;
   String email;

   // Getters/Setters
}

控制器

@GetMapping("/myTable")
public ModelAndView getMyTable(ModelAndView mav) {
   mav.setViewName("myTable");
   List<Request> requests = service.getRequests();
   mav.addObject("requests", requests);
   mav.addObject("requestIds", new ListOfIds());
   return mav;
}

@PostMapping("/myTable")
public ModelAndView postRequests(ModelAndView mav, @ModelAttribute("requestIds") ListOfIds ids) {
   ...
}

html页面

...
<form method="post" th:action="@{/myTable}" th:object="${requestIds}">
   <table class="table ...">
      <thead>
      <tr>
         <th><input type="checkbox" class="selectall" data-target="requests-all"/></th>
         <th>Name</th>
         <th>Phone</th>
         <th>Email</th>
      </tr>
      </thead>
      <tbody>
      <tr role="row" th:each="request : ${requests}">
         <td>
            <input type="checkbox" name="requestId" data-target="requests-all" 
                   th:value="${request.id}" th:field="*{requestIds}"/>
         </td>
         <td th:text="${request.name}"></td>
         <td th:text="${request.phone}"></td>
         <td th:text="${request.email}"></td>
      </tr>
      </tbody>
   </table>
   <button class="btn btn-primary show-selected">Process</button>
</form>
...
<script>
$(document).ready(function() {
   $('button').click(function(e) {
      if !(confirm("Are you sure you wish to process these requests")) {
         e.preventDefault();
      }
   });
});
</script>
...

标签: javaspringthymeleaf

解决方案


所以答案是,name不要th:field一起玩好。

我进行了以下更改并且有效:

控制器

@PostMapping("/myTable")
public ModelAndView postRequests(ModelAndView mav, 
                                 @ModelAttribute("requestIds") Long[] ids) {
   ...
}

html

<form id="postMyTable" method="post" th:action="@{/myTable}">
<table ...
     <input type="checkbox" name="requestId" data-target="requests-all" 
                   th:value="${request.id}"/>
...
<script>
   $(document).ready(function() {
   $('button').click(function(e) {
      if !(confirm("Are you sure you wish to process these requests")) {
         e.preventDefault();
      } else {
         $("#postMyTable").submit();
      }
   });
});
</script>

推荐阅读