简体   繁体   English

在@ModelAttribute注释方法中返回Spring模型

[英]Returning a Spring Model in a @ModelAttribute annotated method

Can I use a Spring model as a model in a method annotated with the @ModelAttribute? 我可以在使用@ModelAttribute注释的方法中将Spring模型用作模型吗? I get an error saying it can't find the attribute in the model. 我收到错误,说它无法在模型中找到该属性。

Here is the method where I add my object to the model: 这是我将对象添加到模型的方法:

@ModelAttribute("survivor")
public Model getSurvivors(Model m) {
    m.addAttribute("decedent", new Decedent());

    return m;
}

Here is the render method. 这是渲染方法。 It prints 'model contains decedent=true' 它打印'model contains decedent = true'

@RenderMapping(params="render=survivors")
public String showSurvivors(Model model, RenderRequest request, RenderResponse response) throws Exception {
    logger.info("in showSurvivors");
    logger.debug("model contains decedent={}, mode.containsAttribute("decedent");
    return "survivors";
}

Here is the jsp: 这是jsp:

<form:form commandName="survivor" action="${submitAction}">
<form:input path="decedent.firstName" />

Error: 错误:

org.springframework.web.servlet.tags.RequestContextAwareTag doStartTag Invalid property 'decedent' of bean class [org.springframework.validation.support.BindingAwareModelMap]: Bean property 'decedent' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? org.springframework.web.servlet.tags.RequestContextAwareTag doStartTag bean类的无效属性'decedent'[org.springframework.validation.support.BindingAwareModelMap]:Bean属性'decedent'不可读或具有无效的getter方法:是否返回getter的类型与setter的参数类型匹配?

You are in essence doing this: 你本质上是这样做的:

model.addAttribute("survivor", model);

The issue that you are seeing in the form:input is that it is expecting a getter decedent on model which does not exist. 您在form:input中看到的问题form:input是期望模型上的getter decedent不存在。 The fix could be to use another wrapper type on top of a normal Map: 修复可能是在普通Map上使用另一个包装器类型:

public class MyCommand{
    private Map<String, Decedent> decedents;
...getters and setters.
}

.. ..

model.addAttribute("survivor", ..); //Add MyCommand type..

.. ..

<form:form commandName="survivor" action="${submitAction}">
<form:input path="decedents['decedent']" />

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

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