9

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

2 Answers 2

11

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Unfortunately the place I need that functionality in is not a controller and I don't know at compile time the type of the backing object.
@MatteoRolla Check the WebDataBinder class for hints, but, as far as I know, the functionality you're looking for doesn't exist out of the box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.