[英]Binding from Set to <form:select> in SpringMVC
我正在使用Spring MVC創建Web,我仍然是Spring的初學者。 我有兩個實體,有很多關系。 在實踐中,我有UserGroup,它可以有多個或一個(或沒有)UserAuthority我想使用具有多個select的表單來編輯這些關系。 創建新的UserGroup實體或編輯現有的實體工作正常,只有一個小問題:編輯現有的UserGroup時,沒有在選擇框中選擇適當的權限。 我已經在這方面工作了一天多沒有成功。 有人可以幫幫我嗎?
我的實體模型是:
@Entity
public class UserGroup {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_group_has_user_authority",
joinColumns = {
@JoinColumn(name = "user_group_id")},
inverseJoinColumns = {
@JoinColumn(name = "user_authority_id")})
private Set<UserAuthority> authorities;
}
(我遺漏了getter和setter,但我的代碼中有它們)
和
public class UserAuthority {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String code;
private String name;
}
(再次,我遺漏了制定者和吸氣者)。
我的表單看起來像這樣:
<form:form action="${action}" method="post" commandName="userGroup" id="user-group-form">
<form:input readonly="true" cssClass="dn" path="id"/>
<table>
<tr>
<td>
<form:label path="title">Title</form:label>
<form:errors path="title" />
</td>
<td>
<form:input path="title"/>
</td>
</tr>
<tr>
<td>
<form:label path="authorities">Authorities</form:label>
<form:errors path="authorities" />
</td>
<td>
<form:select path="authorities" multiple="true" items="${authoritiesList}" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form:form>
我的控制器方法如下:
@RequestMapping(value = "/editGroup", method = RequestMethod.GET)
public ModelAndView editGroup(Model model, HttpServletRequest request) {
Long id = null;
UserGroup userGroup = null;
HashMap<String, Object> editModel = new HashMap<>(2);
try {
id = Long.parseLong(request.getParameter("id"));
} catch (NumberFormatException ex) {
}
if (id != null) {
userGroup = groupsManager.get(id);
}
UserGroupData userGroupData = groupsManager.createFromUserGroup(userGroup);
editModel.put("userGroup", userGroupData);
editModel.put("authoritiesList", getAuthoritiesList());
return new ModelAndView("/users/groupEdit", editModel);
}
@RequestMapping(value = "/editGroup", method = RequestMethod.POST)
public String updateGroupAction(@ModelAttribute("userGroup") @Validated UserGroupData userGroupData, BindingResult result, Model model, HttpServletRequest request) {
if (result.hasErrors()) {
model.addAttribute("userGroup", userGroupData);
return "/users/groupEdit";
}
groupsManager.saveUserGroupData(userGroupData);
return "redirect:/users/listGroup";
}
private Map <Long, String> getAuthoritiesList() { //I also tried returning Map<String,String> but result was same.
Map<Long,String> authorities = new LinkedHashMap<>();
for (UserAuthority ua : authorityManager.getAll()) {
authorities.put(ua.getId(), ua.getName());
}
return authorities;
}
Finnaly,我使用這個轉換器從String創建UserAuthority(實際上我在某處搜索了這個,但它可以工作:))public class StringToUserAuthorityConverter實現Converter {
/**
* The string that represents null.
*/
private static final String NULL_REPRESENTATION = "null";
@Autowired
private UserAuthorityDao authorityDao;
@Override
public UserAuthority convert(final String id) {
if (id.equals(NULL_REPRESENTATION)) {
return null;
}
Long lId = null;
try {
lId = new Long(id);
} catch (NumberFormatException e) {
}
return authorityDao.find(lId);
}
}
正如我所說,所有創建和編輯工作,只有我遇到的問題是,在編輯現有組時,未選擇已與組關聯的權限。 任何幫助將不勝感激。
編輯
我發現了兩件事,也許它會有所幫助:
1)在html頁面中,有以下字段:
<input type="hidden" value="1" name="_authorities">
我讀過它應該包含我的權限字段表單模型的值,但無論如何,它在我的情況下總是包含1
2)如果我的表單未通過驗證(這意味着如果我沒有輸入Title,這是強制性的)表單重新加載並顯示錯誤消息,但是選擇框為空。 不是它的標志嗎?
編輯2
我從上次編輯中解決了第2點...
您需要在Authority
實體類中實現equals()
和hashCode()
方法。 這是因為Set
(和其他集合)檢查對象是否相等,這就是Spring標記已經選擇的字段的方式。
所以我做了一個丑陋的解決方案。 雖然它有效,但代碼並不像我希望的那樣好。 我在jsp中編輯了我的表單,如下所示:
<form:select path="authorities" multiple="true" >
<c:forEach var="authority" items="${authoritiesList}">
<c:choose>
<c:when test="${userGroup.authorities.contains(authority) eq true}">
<option value="${authority.id}" selected="selected">${authority.name}</option>
</c:when>
<c:otherwise>
<option value="${authority.id}">${authority.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
但必須有更好的方法......
您應該使用AutoPopulatingList進行轉換,此功能在Spring中可用於將列表數據轉換為模型列表。 例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.