上下文
我在两个实体之间有一个简单的关联 -Category
and Email
(NtoM)。我正在尝试创建用于浏览和管理它们的网络界面。要浏览类别并将电子邮件添加到该类别中,我使用包含以下内容的控制器@RequestMapping
带有类别 ID (UUID),因此所有控制器操作始终在路径指定的类别上下文中发生。
I use @ModelAttribute
为整个控制器范围预加载上下文类别。
问题
这种方法对于列出和显示表单非常有效。然而,它在表单提交时失败 - 经过一些调试后,我发现表单数据覆盖了我的类别@ModelAttribute
范围。
在我的代码中,在方法中save()
the category
并不是真正加载的模型属性addCategory()
方法,但填充了表单数据(email
模型也已填充,这是正确的)。
我正在寻找允许我将表单数据仅绑定到特定的解决方案@ModelAttribute
.
我在 Spring MVC 文档中读到参数的顺序很重要,但我根据示例对它们进行了排序,但它仍然无法按预期工作。
The code
这是我的控制器:
@Controller
@RequestMapping("/emails/{categoryId}")
public class EmailsController
{
@ModelAttribute("category")
public Category addCategory(@PathVariable UUID categoryId)
{
return this.categoryService.getCategory(categoryId);
}
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Set.class, "categories", new CategoriesSetEditor(this.categoryService));
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createForm(@ModelAttribute Category category, Model model)
{
// here everything works, as there is just a single @ModelAttribute
return "emails/form";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
@ModelAttribute @Valid Email email,
BindingResult result,
Model model,
@ModelAttribute("category") Category category
) {
// saving entity, etc
// HERE! problem is, that response is bound BOTH to `email' and `category' model attributes
// and overrides category loaded in `addCategory()' method
return String.format("redirect:/emails/%s/", category.getId().toString());
}
}
以防万一,这里还有表单代码:
<form:form action="${pageContext.request.contextPath}/emails/${category.id}/save" method="post" modelAttribute="email">
<form:hidden path="id"/>
<fieldset>
<label for="emailName"><spring:message code="email.form.label.Name" text="E-mail address"/>:</label>
<form:input path="name" id="emailName" required="required"/>
<form:errors path="name" cssClass="error"/>
<label for="emailRealName"><spring:message code="email.form.label.RealName" text="Recipient display name"/>:</label>
<form:input path="realName" id="emailRealName"/>
<form:errors path="realName" cssClass="error"/>
<label for="emailIsActive"><spring:message code="email.form.label.IsActive" text="Activation status"/>:</label>
<form:checkbox path="active" id="emailIsActive"/>
<form:errors path="active" cssClass="error"/>
<form:checkboxes path="categories" element="div" items="${categories}" itemValue="id" itemLabel="name"/>
<form:errors path="categories" cssClass="error"/>
<button type="submit"><spring:message code="_common.form.Submit" text="Save"/></button>
</fieldset>
</form:form>
Note:我不想要多个@ModelAttribute
来自 POST,只是想以某种方式将表单模型与之前生成的属性区分开来。