从thymeleaf

时间:2017-04-26 13:44:09

标签: java spring spring-boot thymeleaf

我有一个带有弹簧靴/百里香的简单项目,我有一个关于从百里香洞访问一个物体的问题。  我有我的用户和角色对象。这是我的用户实体:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(unique = true)
    private String username;
    private String password;
    private int enabled;
    @ManyToOne
    private Role role;

    // getters and setters...

}

和角色实体:

@Entity
@Table(name = "roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String role;

    // getters and setters...
}

我正在提供对象的控制器:

@RequestMapping(value = "edit", method = RequestMethod.GET)
public ModelAndView editRoles(){
    ModelAndView modelAndView= new ModelAndView();
    modelAndView.addObject("users", userService.getAll());
    modelAndView.addObject("roles", roleService.getAll());
    modelAndView.setViewName("editRole");
    System.out.println(userService.findUser(2).getRole().getRole());
    return modelAndView;
}
在页面上

,我试图用选择框编辑用户角色。我希望它将用户角色显示为选定值。但它不起作用。这是代码:

<tr th:each="user : ${users}">
    <td >
        <select class="form-control" id="sel1" th:field="*{roles}" >
            <option th:each="role : ${roles}" th:value="${role.id}" th:text="${role.role}" th:selected="${user.role.role}">
            </option>
        </select>
    </td> 
</tr>

问题在于user.role.role部分。它给出了

  

SpringEL表达式

错误。

当我使用user.role时,我可以访问角色对象;但我不能使用角色的属性。 有趣的是,当我使用完全不同的实体和完全相同的配置时,我没有收到任何错误。

有人能告诉我这里有什么问题吗?

1 个答案:

答案 0 :(得分:0)

<强>控制器

@RequestMapping(value = "/create", method = RequestMethod.GET)
public String method1(Model model, Principal principal) {
    model.addAttribute("editRole", roles);
    return "HTML_NAME";
}

控制器2

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String campaignPost(@ModelAttribute("roles") Roles roles,  Principal principal){
    roles.getName();
    //roles object can be accessed
}

<强> HTML

<form th:action="@{/edit}" method="post" id="formName">
    <select class="form-control" th:value="${objectparamater}" name="gender" id="gender">
        <option disabled="disabled" selected="selected" > -- select the location --</option>
        <option>male</option>
        <option>female</option>
        <option>choose not to tell</option>
    </select>
</form>

我想这可能有助于你

相关问题