简体   繁体   English

Spring MVC绑定到错误的字段

[英]Spring MVC binding to wrong fields

I have a controller with 2 methods that return related objects via the @ModelAttribute annotation: 我有一个带有2个方法的控制器,它们通过@ModelAttribute批注返回相关对象:

@ModelAttribute("site")
public Site getSite(){
.....
return site;
}

@ModelAttribute("document")
public Document getDocument(){
.....
return document;
}

These objects are related to each other with one Site having many Documents. 这些对象彼此关联,因为一个站点具有许多文档。 This relationship is mapped in JPA. 此关系在JPA中映射。 Both of these objects contain a field with the same name, called "urlAlias". 这两个对象都包含一个具有相同名称的字段,称为“ urlAlias”。 This field is edited on a page using the following freemarker markup: 使用以下freemarker标记在页面上编辑此字段:

<@spring.bind "document" />
....
<@spring.formInput "document.urlAlias" />

When I submit the form to the controller, I retrieve the document object using the following syntax: 当我向控制器提交表单时,我使用以下语法检索文档对象:

@RequestMapping(method = RequestMethod.POST)
    public ModelAndView create(@ModelAttribute("document") @Valid Document document, BindingResult documentResult,
            @ModelAttribute("site") Site site, Model model){
...Do Stuff...
}

It appears that any value that I enter into the Document's urlAlias field has also been set in the Site object, even though I only edited the value of the field in the Document object. 看来,即使我仅在Document对象中编辑了该字段的值,我在Document的urlAlias字段中输入的任何值也已在Site对象中设置。

I'm perplexed as to what is going on here. 我对这里发生的事情感到困惑。 Am I doing something untoward by mapping more than one ModelAttribute in the same controller? 我是否通过在同一控制器中映射多个ModelAttribute来做某事? Are there any other likely causes of this behaviour? 还有其他可能导致此行为的原因吗?

It would appear that the problem is the site parameter in the create() method in my controller: 看来问题出在我的控制器的create()方法中的site参数:

@ModelAttribute("site") Site site

Removing that stops Spring binding to fields in that object. 删除将停止Spring绑定到该对象中的字段。 For future googlers, I get hold of the Site object within the create() method using the code below instead: 对于未来的Google员工,我使用以下代码代替了create()方法中的Site对象:

if (!model.containsAttribute("site")) {
    throw new IllegalArgumentException("Model must contain site attribute.");
}
Site site = (Site) model.asMap().get("site"); 

From this it would appear that it is fine to declare more than one ModelAttribute in a controller, but only one can be used at a time as a parameter in a method. 由此看来,在一个控制器中声明一个以上的ModelAttribute很好,但是一次只能将一个用作属性中的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM