项目中,往往有从表单到值对象的映射。
以下是一个通用的类:
public class ObjectMapping
{
/**
* 映射html表单为对应的vo对象,当前可以映射String,int,double,boolean,float
* @param 对应的vo对象
* @param request HttpServletRequest
* @return 映射后的对象
*/
public static Object mappingFieldsToObject(Class c, HttpServletRequest request)
{
// 得到所有的请求参数
Enumeration enums = request.getParameterNames();
Object o = null;
try
{
o = c.newInstance();
}
catch (InstantiationException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
// 从JavaBean中得到所有的方法
Method[] methods = c.getDeclaredMethods();
String tem1 = "";
while (enums.hasMoreElements())
{
tem1 = (String) enums.nextElement();
if (tem1 != null && !"".equals(tem1))
{
String methodName = "set" + tem1.substring(0, 1).toUpperCase();
if (tem1.length() > 1)
{
methodName += tem1.substring(1);
}
for (int i = 0; i < methods.length; i++)
{
if (methodName.equals(methods[i].getName()))
{
Method method = methods[i];
if (method.getParameterTypes()[0] == String.class)
{
String param = null2String(request
.getParameter(tem1));
try
{
method.invoke(o, new Object[]{param});
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("注入值时出错");
}
}
else if (method.getParameterTypes()[0] == int.class)
{
String param = null2Zero(request.getParameter(tem1));
Integer intParam = null;
try
{
intParam = Integer.valueOf(param);
}
catch (NumberFormatException e1)
{
intParam = new Integer(0);
}
try
{
method.invoke(o, new Object[]
{
intParam
});
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("注入值时出错");
}
}
else if (method.getParameterTypes()[0] == float.class)
{
String param = null2Zero(request.getParameter(tem1));
Float floatParam = null;
try
{
floatParam = Float.valueOf(param);
}
catch (NumberFormatException e1)
{
floatParam = new Float(0.0F);
}
try
{
method.invoke(o, new Object[]
{
floatParam
});
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("注入值时出错");
}
}
else if (method.getParameterTypes()[0] == double.class)
{
String param = null2Zero(request.getParameter(tem1));
Double doubleParam = null;
try
{
doubleParam = Double.valueOf(param);
}
catch (NumberFormatException e1)
{
doubleParam = new Double(0);
}
try
{
method.invoke(o, new Object[]
{
doubleParam
});
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("注入值时出错");
}
}
else if (method.getParameterTypes()[0] == boolean.class)
{
String param = null2String(request
.getParameter(tem1));
if (!"true".equals(param))
{
param = "false";
}
Boolean booleanParam = Boolean.valueOf(param);
try
{
method.invoke(o, new Object[]
{
booleanParam
});
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("注入值时出错");
}
}
break;
}
}
}
}
return o;
}
private static String null2Zero(String str)
{
if (str == null || "".equals(str.trim()))
{
return "0";
}
return str.trim();
}
private static String null2String(String str)
{
if (str == null)
{
return "";
}
return str.trim();
}
}