Map集合保存数据库

来源:互联网 发布:算法工程师年薪 编辑:程序博客网 时间:2024/06/07 19:31
1.Map<String, String> paramsMap = new HashMap<String, String>();
            List<FileItem> itemList = sf.parseRequest(request);
            // 1.上传
            for (FileItem fileItem : itemList) {
                if (!fileItem.isFormField())// 判断是否为上传组件
                {
                    // 1.1执行上传
                    // 1.1.1获取服务器上传目录路径
                    String path = getServletContext().getRealPath("/products");
                    // 1.1.2上传
                    InputStream is = fileItem.getInputStream();
                    // getFieldName()获取表单标签name属性值
                    // getName()获取文件名
                    // getString()获取表单标签value值
                    FileOutputStream fos = new FileOutputStream(new File(path,
                            fileItem.getName()));
                    IOUtils.copy(is, fos);
                    // 清除临时文件
                    fileItem.delete();
                    is.close();
                    fos.close();
                    // 将pimage属性存入map
                    paramsMap.put(fileItem.getFieldName(), "products/"
                            + fileItem.getName());
                } else// 普通组件
                {
                    paramsMap.put(fileItem.getFieldName(),
                            fileItem.getString("UTF-8"));
                }

            }
            // 2.封装product对象 保存到数据库里
            Product product = new Product();

            BeanUtils.populate(product, paramsMap);

2.Map<String,String[]> paramMap = request.getParameterMap();
        Category category = new Category();
        BeanUtils.populate(category, paramMap);

3.Map<String, String[]> properties = request.getParameterMap();
        User user = new User();

        // 自定义类型转换器
        // 参数1:类型转换器
        // 参数2:要转换至的类型
        ConvertUtils.register(new Converter() {

            @Override
            // 参数一:要转换成的类型
            // 参数二:要转换的对象
            public Object convert(Class arg0, Object arg1) {
                // TODO Auto-generated method stub
                // 将字符串转data
                System.out.println(arg0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return sdf.parse(arg1.toString());
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
        }, Date.class);
        // 封装属性
        BeanUtils.populate(user, properties);

总结:首先,用map集合保存对象必须前台jisp页面input属性name和数据库字段名保持一致,否则无法存入数据。

           然后,当map集合存入图片时,要用Map<String, String> paramsMap = new HashMap<String, String>();

                      当map集合不存图片时,要用Map<String, String[]> properties = request.getParameterMap();



自我小结:总结的不是多好,但勉强还能看懂。所以要更加努力,争取一次比一次好。加油!!!