[英]Spring and Hibernate: How to modify user authorities using jsp and checkboxes
我正在使用Spring Security並有一個admin jsp頁面,用於編輯用戶詳細信息。 我希望能夠授予或撤消此頁面上的權限。 以下復選框標簽可顯示給定用戶的現有權限:
<form:checkboxes path="authorities" items="${roles}" delimiter="<br />" />
其中authorites
是用戶實體的屬性,而${roles}
是模型屬性,該模型屬性是所有可能的權限的列表。
這適用於GET:如果我在此頁面中查詢用戶,則會列出所有權限,並檢查用戶的權限。
問題是,如果我更改了用戶權限(添加新權限或刪除現有權限)並嘗試保存,則會出現以下錯誤:
HibernateSystemException: IllegalArgumentException occurred calling getter of com.ebisent.domain.Authority.id
我在調試器中看到,Hibernate將我的Set<GrantedAuthority> authorities
包裝在org.hibernate.collection.PersistentSet
。 Hibernate不會將新權限添加到我的權限集中。 而是添加一個新的Set,其中包含授權的字符串值。 結果是我的權限HashSet(應該只包含GrantedAuthority元素)現在包含LinkedHashSet,這些鏈接包含我要添加的權限的字符串表示形式。
這是User.authorities的獲取器和設置器:
public Set<GrantedAuthority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<GrantedAuthority> authorities) {
this.authorities = authorities;
}
我究竟做錯了什么?
這是HTML表單的固有限制-由於HTML表單中的字段值表示為字符串,因此您需要指導Spring如何從字符串表示中重建GrantedAuthority
。 可以按照以下步驟完成:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(GrantedAuthority.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
GrantedAuthority value = ...;
setValue(value);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.