自己二次封装的Unils类
package cn.day1201.utils;
import java.util.Map;
import java.util.UUID;import org.apache.commons.beanutils.BeanUtils;
public class CommonUtils {
//生成不重复的32位长的大写字符串
public static String unid() {
return UUID.randomUUID().toString().replace("_", "").toUpperCase();
}
//把map转换成指定类型的javabean对象
public static <T> T toBean(Map map,Class<T> clazz){
try {
//创建指定类型的javaBean对象
T bean = clazz.newInstance();
//把数据封装到javaBean中
BeanUtils.populate(bean, map);
//返回javaBean对象
return bean;
}catch(Exception e) {
throw new RuntimeException(e);
}
}
}
使用它 ,
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");System.out.println(username + "|" + password);
Map<String, String> map = new HashMap();
map.put("username","zhangsan");
map.put("password", "123456");
User u = CommonUtils.toBean(map, User.class); //此处就是调用它的方法
System.out.println(u);
User u2 = CommonUtils.toBean(req.getParameterMap(), User.class); //此处就是调用它的方法
System.out.println(u2);
}
如果有问题可以去群里问,博客首页有QQ群