niklassaers
niklassaers

Reputation: 8830

Spring 3.0M4 and passing objects as parameters to POST

I'm quite sure this has to be in the docs somewhere, but I've looked for days and haven't spotted it. I'm probably staring myself blind when it's right in front of me, so sorry for asking an abvious question, but....

@RequestMapping(method = RequestMethod.POST)
public ModelAndView post(@ModelAttribute("user") User user) {
  ModelAndView mav = new ModelAndView(jsonView);
  //....
  return mav;
}

This is my POST function as part of my controller, and I'd like to try it out. So I fire up Poster, the Firefox REST tester that I use for trying out my functions, and fire a POST to http://localhost:8000/userController with parameters { firstname = "foo", lastname = "bar }. That gives me:

org.springframework.web.HttpSessionRequiredException: Session attribute 'user' required - not found in session

So I try with { user.firstname = "foo", user.lastname = "bar" }, same error. What parameters do I need to send in a POST or PUT request in order to use this mechanism that automatically maps my parameters to an object?

Cheers

Nik

Upvotes: 1

Views: 3369

Answers (3)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83161

That effect apparnetly occurs if you have @SessionAttributes annotation at your class. This causes Spring to expect the model attribute to be stored in the session from a prior GET web request, that put the object into the model.

This behaviour allows partial binding of request parameters to model objects. The workflow is as follows:

  1. you receive a GET request to populate the model
  2. Spring binds all model objects you configured either by name or type in @SessionAttributes to the session
  3. you receive a POST request with updated data
  4. Spring takes the objects from the session and binds the request data to them

Othwerise Spring would populate an empty new object which is mostly not the desired behaviour.

Upvotes: 1

skaffman
skaffman

Reputation: 403581

No annotation should be necessary on the User method parameter, Spring will recognise it as a command object and bind to it without the annotation.

@ModelAttribute is slightly confusing, I find, its meaning seems to vary from situation to situation.

Upvotes: 0

rodrigoap
rodrigoap

Reputation: 7480

That annotation will search in the session an attribute named 'user', while the parameters you send in the POST are stored as parameters of the request:

//Get a session attribute:  
request.getSession().getAttribute("user");

//Get a request parameter:
request.getParameter("firstname");

More here

Upvotes: 1

Related Questions