2017-05-23 89 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教程。

相关问题