如何通过Thymeleaf向用户添加角色

时间:2018-09-26 10:42:45

标签: java html spring thymeleaf crud

在添加新用户的控制器中,我尝试通过与百里香编织来添加角色选择(管理员或用户)

控制器

@RequestMapping(value = "admin", method = RequestMethod.POST)
public String addPost(@ModelAttribute User user) {
    userService.addUser(user);
    return "redirect:/admin";
}

@RequestMapping(method = RequestMethod.POST)
public String createUserRole(Model model) {
    model.addAttribute("roles", roleService.getRoleByRoleName("ADMIN"));
    model.addAttribute("roles", roleService.getRoleByRoleName("USER"));
    return "admin";
}

admin.html

<h4> Add user</h4>
<form method="post" accept-charset="UTF-8">
Enter Username <input type="text" name="name" > <br>
Enter Password <input type="password" name="password" > <br>

<label><select required name="roles">
     <th:block th:each="role : ${roles}">
         <tr>
             <td th:text="${role.id}"></td>
             <option><td th:text="${role.roles}">ADMIN</td></option>
         </tr>
        </th:block>
</select>
</label> Role <br>
<button type="submit" name="create" >create</button>

我知道我尝试在百里香中选择角色的尝试是不正确的。 我尝试了很多选择

<td th:text="${roles.setRoleName('USER')}">USER</td>

添加具有用户或管理员角色的操作是通过添加到控制器来完成的,但是如何添加角色之间的选择?

@RequestMapping(value = "admin", method = RequestMethod.POST)
public String addPost(@ModelAttribute User user) {
    Role roleUser = roleService.getRoleByRoleName("USER");
    Set<Role> roles = new LinkedHashSet<>();
    roles.add(roleUser);
    user.setRoles(roles);
    userService.addUser(user);

    return "redirect:/admin";
}

我将不胜感激!

0 个答案:

没有答案