Pergunta

Can I use a Spring model as a model in a method annotated with the @ModelAttribute? 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'

@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:

<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?

Foi útil?

Solução

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. The fix could be to use another wrapper type on top of a normal 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']" />
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top