Reputation: 5430
I am developing a Java web project and not applying Spring MVC, Spring web-flow to it (because it is quite simple). I have a small problem when attaching value from HTTP request to Java object. Is there any standalone library or utility support us to bind data from client request to a server object automatically (matched by property name) without using Spring? Assume that parameters in client request had already built to a map.
When I work with Grails (a web framework for Groovy), it has a very awesome way to fill data in request parameter to object by using: object.properties=parameters
, but I do not know that in Java, do we have a similar mechanism to implement it?
Thank you so much.
Upvotes: 0
Views: 511
Reputation: 14529
Apache Commons might help with BeanUtilsBean. It has cool methods like getProperty()
and setProperty()
, which might help if you wanna try to code it by hand using reflection. There's also the populate(Object bean, Map properties)
method, which, i believe, is the closest to what you want.
Dozer is a java library specialized in mapping stuff from one structure to other. It might help.
This guy posted a similar question on coderanch and, after some discussion, he came up with the following:
public static <T extends Object> T setFromMap(Class<T> beanClazz, HashMap<String, String> propValues) throws Exception
{
T bean = (T) beanClazz.newInstance();
Object obj = new Object();
PropertyDescriptor[] pdescriptors = null;
BeanInfo beanInfo = Introspector.getBeanInfo(beanClazz);
pdescriptors = beanInfo.getPropertyDescriptors();
for(int i=0; i<pdescriptors.length; i++)
{
String descriptorName = pdescriptors[i].getName();
if(!(descriptorName.equals("class")))
{
String propName = descriptorName;
String value = (String) propValues.get(propName);
if(value != null)
{
Object[] objArray = new Object[1];
objArray[0] = value;
Method writeMethod = pdescriptors[i].getWriteMethod();
writeMethod.invoke(bean, objArray);
}
}
}
return bean;
}
Upvotes: 2