简体   繁体   中英

How does Spring MVC turn form values into objects?

I'm using Spring 3.0.

I know that when my controller gets invoked, my form bean gets populated by the Spring by evaluating the request parameters and do the necessary conversions.

Let's say I have the following markup

<form action="test">
  <input type="text" name="user.username"/>
  <input type="submit" value="save"/>
</form>

And I have the following controller and classes:

public class MyController
{
  @RequestMapping(...)
  public void myHandler( @ModelAttribute MyForm myForm, ResultBinding result )
  {
    // do something here
  }
}

public class MyForm
{
  private User user;

  // Getters and setters included
}

public class User
{
  private username;

  // Getters and setters included
}

My problem is that Spring MVC is not using any of my setters to set the properties of my objects. Is there something that I could do to force Spring MVC to use the setters to set the properties of my objects? Where in the Spring documentation that says how Spring does this?

Spring MVC为此使用PropertyEditorSupport的实现。

You need to annotate your method parameter with @ModelAttribute :

public void myHandler( @ModelAttribute("myForm") MyForm myForm, ResultBinding result )

And have a method to provide an instance of your model object:

@ModelAttribute("myForm")
public MyForm getMyForm() {
  return new MyForm();
}

See this: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM