Thymeleaf传递对象的集合作为对象的成员到控制器

时间:2017-05-23 18:42:27

标签: model-view-controller spring-boot thymeleaf

我有一张表格:

<form action="#" th:action="@{/private/createUser}" th:object="${toCreate}" method="post">

<label for="alias">User Alias</label>
<input id="alias" type="text" th:field="*{alias}"/>

<label for="fullName">Full Name</label>
<input id="fullName" type="text" th:field="*{fullName}"/>

<label for="password">Password</label>
<input id="password" type="password" th:field="*{password}"/>

<ul for="userRoles">
  <li th:each="role, roleStat : ${availableRoles}">
    <div>
      <label th:for="${roleStat.count}" th:text="${role.name}">Role Name</label>
      <input th:id="${roleStat.count}" type="checkbox" th:value="${role}"/>
    </div>
  </li>
</ul>

<button type="submit" th:text="Submit" name="submitButton"></button>

</form>

那应该向我的控制器提供一个User对象:

@Controller
public class UserCreationController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/private/createUser", method = RequestMethod.GET)
    public String createUser(Model m) {
        m.addAttribute("availableRoles", UserRole.values());

        m.addAttribute("toCreate", new User());

        return "createUser";
    }

    @RequestMapping(value = "/private/createUser", method = RequestMethod.POST)
    public String createUserPost(@ModelAttribute("toCreate") User toCreate, Model m, HttpServletResponse response) {
        FlexibleResponse resp = userService.createUser(toCreate);
        if (resp.isPositive()) {
            m.addAttribute("success", resp.getContent());
        } else {
            m.addAttribute("failure", resp.getContent());
        }

        response.setStatus(resp.isPositive() ? 200 : HttpServletResponse.SC_BAD_REQUEST);
        return "redirect:createUser";
    }
}

除了&#34; userRoles&#34;之外,一切都运行顺畅,这是一个Set<UserRole> userRoles; UserRole是一个枚举(你可以通过查看控制器来判断)。我需要做什么才能将这些复选框绑定为th:object="${toCreate}"内的一个Set?

1 个答案:

答案 0 :(得分:1)

您缺少th:field角色复选框输入。没有它,就不会生成所需的name属性。试试这个:

<label th:for="${#ids.next('userRoles')}" th:text="${role.name}">Role Name</label>
<input type="checkbox" th:field="*{userRoles}" th:value="${role}"/>

参考:Thymeleaf教程中的Checkbox fields部分。