0
我有一種形式: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>
這是應該提供用戶對象到我的控制器:
@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<UserRole> userRoles;
UserRole是一個枚舉(你可以通過查看控制器來判斷)。爲了將這些複選框作爲我的th:object="${toCreate}"
中的Set綁定,需要做什麼?