0

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.

1
  • 1
    I didn't understand your reason for not using Spring. In my opinion it is exactly the thing you want to use for something like this. Commented Nov 4, 2012 at 16:31

1 Answer 1

2

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

Comments

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.