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

本文介绍了一种解决前端图片上传时,后台使用MultipartHttpServletRequest接收参数的问题,并提供了一个将请求参数转化为自定义模型的方法,避免了直接使用request接收参数带来的不便。

当前端需要传图片时,后台用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;
}
 

 

转载于:https://www.cnblogs.com/wenjing-520/p/9364366.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值