Reputation: 257
Is there a way to programmatically bind form data to an object knowing the class type? I thought there would be something like
T instance = something.pleaseDoSomeMagicBind(class, request)
somewhere or something similar, but I had no luck so far.
Thank you
Upvotes: 9
Views: 2057
Reputation: 257
Thanks to Sotirios (you saved my sanity) hint, I've been able to achieve what I've been looking for and I'm leaving here my findings if anyone else is interested
final WebDataBinder binder = new WebDataBinder(BeanUtils.instantiate(clazz));
ServletRequestParameterPropertyValues values = new ServletRequestParameterPropertyValues(request);
binder.bind(values);
final BindingResult result = binder.getBindingResult();
Upvotes: 11
Reputation: 280178
Spring binds form data by mapping request parameters to fields of instances of handler method parameter types based on matching names.
.../asd?someValue=123
will be bound to an instance of
public class Backing {
private String someValue;
//getters and setters
}
assuming you have a request handler like
@RequestMapping
public String handle(Backing backing) {
return backing.getSomeValue(); // "123"
}
Nothing exists like what you are describing.
Upvotes: 1