java后台使用HttpServletRequest接收参数转换为model

当前端需要传图片时,后台用MultipartHttpServletRequest接收参数,request接收过来的参数有很多弊端,需要包装成自己的model就得做转化

弊端:

1.所接收的参数类型无法判断,全是字符串类型的。其余类型都要转,心累。。。。。

2.若传入的参数中含有null,undefined的参数则直接变成了字符串“null”和“undefined”。有天突然看见生产库中多了许多“null”,一脸懵逼。。。。

转化成自己方法的代码:

 
public static <T>T requestParameterToBean(HttpServletRequest request,Class<T> clszz) {
T obj = null;
BeanInfo beanInfo=null;
try {
//获取该类的信息
beanInfo = Introspector.getBeanInfo(clszz);
//实例化该class
obj = clszz.newInstance();
} catch (IllegalAccessException e) {
LOGGER.error("实例化 JavaBean 失败");
} catch (IntrospectionException e) {
LOGGER.error("获取分析类属性失败");
} catch (InstantiationException e) {
LOGGER.error("实例化 JavaBean 失败");
}
//获取该类属性的描述
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
String paramName = (String) en.nextElement();
PropertyDescriptor descriptor;
for(int i=0;i<propertyDescriptors.length;i++){
if(paramName.equals(propertyDescriptors[i].getName())&&!"class".equals(propertyDescriptors[i].getName())){
descriptor = propertyDescriptors[i];
String className = descriptor.getPropertyType().getName();
Method method = descriptor.getWriteMethod();
if (!("undefined".equals(request.getParameter(paramName))||"null".equals(request.getParameter(paramName)))){
Object value;
//这里的类型不一一枚举,若传过来的class还有别的类型,在这里加上
if(className.equals("java.lang.Boolean")){
value = Boolean.parseBoolean(request.getParameter(paramName));
}else if(className.equals("java.lang.Integer")){
value = Integer.parseInt(request.getParameter(paramName));
}else {
value =request.getParameter(paramName);
}
try {
method.invoke(obj, new Object[]{value});
}catch (IllegalAccessException e) {
LOGGER.error("调用set方法失败");
} catch (InvocationTargetException e) {
LOGGER.error("字段映射失败");
}

}
}
}
}
return obj;
}
 

猜你喜欢

转载自www.cnblogs.com/wenjing-520/p/9364366.html