public static void setAttributes(HttpServletRequest req,Object obj) throws Exception{
Map<String, String[]> map=req.getParameterMap();
for (String key : map.keySet()) {
Class objClass = (Class) obj.getClass();
Field[] fs = objClass.getDeclaredFields ();
for(Field f:fs){
f.setAccessible( true );
if(f.getName().equals(key)){
String type = f.getType().toString();
if (type.endsWith( "String" )) {
f.set(obj,map.get(key)[0]);
}else if (type.endsWith( "int" ) || type.endsWith( "Integer" )){
f.set(obj,Integer.valueOf(map.get(key)[0]));
}
}
}
}
}
本文介绍了一种在Java中通过HttpServletRequest对象将请求参数映射到指定对象属性的方法。该方法遍历请求参数,并使用反射机制为对象的相应字段设置值。支持String和Integer类型的数据转换。
1215

被折叠的 条评论
为什么被折叠?



