0
我有一個簡單的項目與春季啓動/百里香,我有這個問題訪問從百里香的對象。 我有我的用戶和角色對象。這裏是我的用戶實體:無法從百里香葉到達目標
@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會爲你做這件事。 – Metroids
多數民衆贊成在使用選擇框的一個問題。你有什麼意見,爲什麼我不能訪問該對象? – qourcam
最主要的原因是你沒有把你的控制器中的對象正確地傳遞給HTML,希望你按照下面顯示的順序:) –