Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Spring MVC - Automatically populate object from form submission?

In ASP.NET MVC in the controller I can just have an object from my model be a parameter in one of my methods, and a form submission that gets handled by that method would automatically populate the object.

eg:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(User u){...}

The user object will automatically be populated for be from the form submission.

Is there a way to have this automatically happen using Spring MVC, and if so how do I do it?

like image 501
Kyle Avatar asked Oct 15 '22 10:10

Kyle


2 Answers

In Spring MVC (with Spring MVC 2.5+ annotation-based configuration) it looks exactly the same way:

@RequestMapping(method = RequestMethod.POST)
public ModelAndView edit(User u) { ... }

The User object will be automatically populated. You may also explicitly specify the name of the corresponding model attribute with @ModelAttribute annotation (by default attribute name is a argument's class name with first letter decapitalized, i.e. "user")

... (@ModelAttrbiute("u") User u) ...
like image 56
axtavt Avatar answered Oct 18 '22 05:10

axtavt


http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/web/portlet/mvc/SimpleFormController.html#onSubmitAction(java.lang.Object)

Create a Form Controller, for example PriceIncreaseFormController and make it extend SimpleFormController

override the method public ModelAndView onSubmit(Object command) there are many variants of the above. look for the right method that suits your need. For simple flow the above method should be sufficient.

Inside the method, you can typecast command and get your Command class.

commandObj = ((PriceIncrease) command)

commandObj will have the parameters populated by spring.

in your springapp-servlet.xml you should tell spring about the PriceIncrease command class as follows and also you should have a POJO for your command class created.

<bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController">
    <property name="commandClass" value="springapp.service.PriceIncrease"/>

....

like image 20
Joseph Kulandai Avatar answered Oct 18 '22 03:10

Joseph Kulandai