How can I populate two beans from my form using Spring MVC?

Therefore, I use Spring MVC 3 with annotations.

I have a simple html form (actually ExtJS) that has three fields.

1) Username 2) Password 3) Color 

OK, so username and password refer 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 am new to Spring, btw.

thanks

+4
source share
1 answer

Usually you should create a new class that represents the form (this is called a form support object), for example, UserColorForm , which contains properties for each of the inputs in the request body.

Your controller method will look like this:

 @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 matching the input names of the form, Spring will associate the input to the request directly with the properties. those. 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 view name from the method ( user.jsp ). @ResponseBody means that the return value of the method must be written directly to the response stream.

+5
source

Source: https://habr.com/ru/post/1434057/


All Articles