2017-05-23 138 views
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綁定,需要做什麼?

回答

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}"/> 

參考:Checkbox fields部分在Thymeleaf教程。

相關問題