public class WebUtils {
private WebUtils(){}
// 将请求参数封装到bean
public static <T> T request2Bean(HttpServletRequest request, Class<T> clazz) {
try {
//创建请求类的对象
T bean = clazz.newInstance();
//添加id
if(request.getParameter("id") == null){
String id = UUID.randomUUID().toString();
BeanUtils.setProperty(bean,"id",id);
}
//注册转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
// 不知道是什么样的表单 什么样的bean 不知道有哪些字段
Enumeration e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = request.getParameter(name);
BeanUtils.setProperty(bean, name, value);
}
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
本文介绍了一种实用的方法,即将HTTP请求中的参数封装到Java Bean中。通过使用反射和第三方工具类,如Apache Commons BeanUtils,实现了一个通用的工具类方法。此方法能自动处理各种类型的请求参数,并将其映射到指定的Java Bean实例上。
509

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



