开发者

Difference between @ModelAttribute and org.springframework.ui.ModelMap.get()?

I'm trying to use an Object as the command object of a <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>element.

In the controller's GET method, I add the Object like this:

@RequestMapping(method = RequestMethod.GET)
public String renderForm(ModelMap model, HttpServletRequest request) {
    [...]
    model.addAttribute("voting", voting);
    [...]
}

The rendered form does show the command object correctly when defined like this:

<form:form action="vote" method="PUT" commandName="voting" name="oform">

Now when trying to access the form's command object back in the controller, on the POST method, I have two approaches. First, I declare the @ModelAttribute in the signature:

@RequestMapping(method = RequestMethod.PUT)
public String newVoting(@ModelAttribute("voting") Voting voting, HttpServletRequest request) { [...]}

Or I access the ModelMap and get the value from the underlying map:

@RequestMapping(method = RequestMethod.PUT)
public String newVoting(ModelMap model, HttpServletRequest request) {
    Voting voting = (Voting) model.get("voting");
    [...]
}

When doing the first, I get the object as it was submitted by the form. Doing the latter, I get the object as it was BEFORE being handled by the form.

Why does the form's submit not change the object in the ModelMap and why does the @ModelAttribute differ from whats in the actual model? I feel like the name 'ModelAttribute' should result in the same object like getting the object directly from the model.

Maybe @ModelAttribute is kind of misleading?

EDIT Forgot to mention th开发者_运维百科at the object is a @SessionAttributes

 @SessionAttributes({"voting", "state"})


Your first approach, using the @ModelAttribute annotation does two things:

  1. Creating the Voting object using the submitted form data;
  2. Exposing the Voting object to the view by adding it to the model (request, or, in your case, session because of the @SessionAttributes({"voting"})).

Your second approach uses just the ModelMap, so it's getting only model attributes (from the request or, in your case, the session, depending on the @SessionAttributes annotation). This approach does not use the data from the submitted form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜