开发者

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

开发者 https://www.devze.com 2022-12-19 10:56 出处:网络
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 ob

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:

开发者_如何学Python
[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?


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) ...


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"/>

....


In Servlets no, but in Spring MVC absolutely. Take a look at the web framework docs.

Specifically Section 13.11.4, 9th bullet point.

0

精彩评论

暂无评论...
验证码 换一张
取 消