Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hire Spring MVC databinder

I read nice comprehensive explanation of spring data binder here: https://stackoverflow.com/a/3705855/1828986

My problem needs little bit more knowledge, let me highlight it:

I have Person object with complex field - e.g. contact with street and number fields. So we can describe it as follow:

public class Contact {
    private String street;
    private int number;
// setters & getters
};
public class Person {
    private String name;
    private int age;
    private Contact contact;
// setters & getters
};

I recognized that spring represent it to html form as followed input fields:
name, age, contact.street, contact.number

I assume, that it can put it back to Person object when gets it back.

I'd like to "hire" spring binder to create object for text data provided by me (not HttpRequest object). For example i have file:

name       age        street       number
John       22         MHDrive      2187
Will       32         MHDrive      3212

I can provide any structure with above and want to get Person object :)

e.g.

Person p = springBinderSomething({{"name","John"},{"age","22"},{"street","MHDrive"},{"number","2187"}}, Person.class);

Any help appreciated
Thx
Saram

like image 887
Saram Avatar asked Oct 20 '25 06:10

Saram


1 Answers

In this case, it sounds like you want to use the DataBinder class directly. You should be able to instantiate an instance of DataBinder passing the instance of the object you want to bind to and then call the bind(PropertyValues) method to do the binding. Spring MVC would typically instantiate a new instance of your class for you, but if you're calling DataBinder directly, you'll need to pass it an instantiated instance instead. ServletRequestDataBinder creates an instance of MutablePropertyValues behind the scenes, which it populates with parameter values from the request, and then passes into the #bind(PropertyValues) method. In your case, you'll probably want to create a new instance yourself and populate it with your data directly instead of from the Request. There are a number of constructors for MutablePropertyValues if you have the data available in existing objects, otherwise you can just call the #add(String, Object) method with your names and values.

Person person = new Person();
DataBinder dataBinder = new DataBinder(person);
MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("name", "John Doe");
mpv.add("age", 25);
mpv.add("contact.street", "1st Street");
mpv.add("contact.number", 12345);
dataBinder.bind(mpv);
like image 116
Jason Day Avatar answered Oct 22 '25 21:10

Jason Day



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!