由于某些特殊原因不能够使用SpringMvc的自动封装去封装对象,故写了工具类,手动从HttpServletRequest中把属性注入到对象中
private void requestToObject(HttpServletRequest request, Object object,Class objective) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
// 递归调用
if(objective.getSuperclass() != Object.class){
requestToObject(request,object,object.getClass().getSuperclass());
}
for (Field field : objective.getDeclaredFields()) {
Enumeration enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
String ele = enumeration.nextElement().toString();
String fileName = field.getName();
if (ele.equals(fileName)) {
Method method = null;
try {
method = objective.getDeclaredMethod("set" + fileName.substring(0, 1).toUpperCase() + fileName.substring(1, fileName.length()), String.class);
} catch (NoSuchMethodException e) {
try {
method = objective.getDeclaredMethod("set" + fileName.substring(0, 1).toUpperCase() + fileName.substring(1, fileName.length()), Integer.class);
} catch (NoSuchMethodException e1) {
throw e1;
}
}
method.setAccessible(true);
method.invoke(object, request.getParameter(field.getName()));
}
}
}
}