views:

993

answers:

3

Hi guys,

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%3A8000/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
A: 

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

rodrigoap
Right, what I guess I'm asking is: how do I set this user attribute in my REST request? Or is 'user' only living on the server-side session?
niklassaers
A: 

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.

skaffman
A: 

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.

Oliver Gierke
Aha! :-) That makes totally sense, so I had misunderstood this part and assumed that Spring mapped values to the requested object so that this could be instantiated or requested. This makes for easy "wizard" processes
niklassaers