Reputation: 8830
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
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:
GET
request to populate the model@SessionAttributes
to the sessionPOST
request with updated dataOthwerise Spring would populate an empty new object which is mostly not the desired behaviour.
Upvotes: 1
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
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");
Upvotes: 1