【问题标题】:Thymeleaf pass Set of Object as member of object to controllerThymeleaf 将对象集作为对象的成员传递给控制器
【发布时间】:2017-10-23 20:55:12
【问题描述】:

我有一个表格:

<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>

这应该为我的控制器提供一个用户对象:

@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";
    }
}

除了“userRoles”,它是一个Set&lt;UserRole&gt; userRoles; UserRole 是一个枚举(你可以通过查看控制器来判断)之外,一切都很顺利。我需要做什么才能将这些复选框绑定为我的 th:object="${toCreate}" 中的 Set ?

【问题讨论】:

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


    【解决方案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 部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多