【发布时间】:2017-04-26 13:44:09
【问题描述】:
我有一个带有 spring boot/thymeleaf 的简单项目,我遇到了关于从 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时,我可以访问角色对象;但我不能使用角色的属性。
有趣的是,当我使用具有完全相同配置的完全不同的实体时,我没有收到任何错误。
谁能告诉我这里有什么问题?
【问题讨论】:
-
th:selected应该评估为真/假,而不是字符串。此外,如果您使用的是th:field,则不必使用th:selected-- thymeleaf 会为您执行此操作。 -
这是使用选择框的一个问题。您对我为什么无法访问该对象有任何意见吗?
-
主要原因是您没有正确地将对象从控制器传递到 HTML,希望您能像我在下面显示的那样遵循 :)
-
我解决了。这是一个菜鸟错误:) 我正在传递对象,但其中有一个空值,这就是问题 :D 感谢你们俩
标签: java spring spring-boot thymeleaf