Reputation: 11420
So I am using Spring MVC 3 with annotations.
I have a simple html form (ExtJS actually) that has three fields.
1) Username
2) Password
3) Color
OK, so username
and password
belong to a databean called User
. color
belongs to another bean called Color
.
In my UserController, I have:
@RequestMapping(value = "/users/login", method = RequestMethod.POST)
@ResponseBody
public String handleLogin( @ModelAttribute("user") User paUser,
@ModelAttribute("color") Color paColor,
ModelMap map) {
// at this point "paUser" contains both username AND password submitted from form
// however, there is nothing in "paColor"
...
return "user.jsp"
}
What am I doing wrong?
I'm new to Spring, btw.
Thanks
Upvotes: 4
Views: 1789
Reputation: 139931
Usually you would create a new class that represents the form (this is known as a form-backing object), such as UserColorForm
, that contains properties for each of the inputs in the request body.
Your controller method would then look like:
@RequestMapping(value = "/users/login", method = RequestMethod.POST)
@ResponseBody
public String handleLogin(UserColorForm form, ModelMap map) {
// now you can work with form.getUsername(), form.getColor() etc.
If the FBO bean has property names that match the form input names, Spring will bind the input in the request directly to the properties. i.e. if the form input is username=matt&color=blue
then Spring will create a new instance of my form and call setUsername("matt")
and setColor("blue")
.
By the way, you probably don't want the method to be annotated with @ResponseBody
if you are going to return the name of the view from the method (user.jsp
). @ResponseBody
means that the return value of the method should be written directly to the response stream.
Upvotes: 5