我有一個帳戶實體與@ManyToMany關係到角色實體。 (這樣我就可以擁有一個擁有多個角色的帳戶)。Spring MVC 3:爲ManyToMany關係添加表單無論是綁定結果異常
在我Account.java(實體)我已經定義的關係如下:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Account_Role", joinColumns = {
@JoinColumn(name = "Account_id") },
inverseJoinColumns = { @JoinColumn(name = "Role_id") })
private List<Role> roles = new ArrayList<Role>(0);
在我的AccountController我有GET和POST以下操作:
@RequestMapping(value="/add", method=RequestMethod.POST)
public String add(Account item, BindingResult bindingResult, Model model, HttpServletRequest request)
{
accountService.save(item);
return "redirect:/account/list";
}
@RequestMapping(value="/add", method=RequestMethod.GET)
public String addForm(Model model) {
model.addAttribute("item", new Account());
model.addAttribute("roleList", roleService.list());
return "account/add";
}
我加。 JSP表單視圖看起來是這樣的:
<form method="post">
<table>
.....
<tr>
<td style="width:75px">
<label for="roles"><spring:message code="labels.account.form.roles" text="Roles" /></label>
</td>
<td>
<form:select path="roles" multiple="true" items="${roleList}" itemLabel="name" itemValue="id"/>
</td>
</tr>
<tr>
<td></td>
<td>
<input id="submitbutton" type="submit" value="<spring:message code="labels.form.button.add" text="Save" />" style="width:100%;">
</td>
</tr>
</table>
當我嘗試打開添加對話框輸入新帳戶我送花兒給人收到以下錯誤:
SEVERE: Servlet.service() for servlet [spring] in context with path [/eLearning] threw exception [Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException: ServletException including path '/WEB-INF/views/template/layout.jsp'.] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'roles' available as request attribute
我真的很感激它來獲得被人一些幫助。我在訪問Attribute Entity的其他字段時沒有問題。它只是「角色」 - 導致問題的屬性。因爲如果我從添加jsp表單註釋掉它,那麼一切工作正常:S。
感謝您的幫助。
編輯:
感謝您的幫助。我沒有得到這個例外了。我現在如何獲得角色的價值? 如果我嘗試訪問控制器中的item.getRoles(),我得到一個空列表。我如何安排通過選擇列表選擇的角色存儲在賬戶實體的角色列表中?
用於解決第二個問題:
這是必要的定製綁定添加到控制器:
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception {
binder.registerCustomEditor(Set.class, "roles", new CustomCollectionEditor(Set.class) {
protected Object convertElement(Object element) {
if (element instanceof Role) {
return element;
}
if (element instanceof String) {
return roleService.load(Long.valueOf(element.toString()));
}
return null;
}
});
}
非常感謝你2我不得到例外... 我怎麼現在可以從控制器中的角色獲取選定的值?如果我打電話 item.getRoles() 我得到一個空的列表...所以我猜實體上的角色屬性沒有設置... – mooonli
@axtavt - 我想這是'