(三十)商品管理-添加商品(上传图片)
添加商品(上传图片)1.修改页面上添加连接/store/adminProduct?method=addUI2.在addUI请求转发到 添加页面3.在表单页面上修改action : /store/addProductServlet提交方式: method="post"添加enctype属性: enctype="multipart/form-data"给每个字段添加name属性4.addProductServlet通过request.getParameterMap获取的信息全部为空我们想使用beanuitls.populate(bean,map),我们需要创建一个map集合 ,将前台接受过来信息手动的put到map中注意:商品的图片:1:保存到服务器的磁盘2.在数据中添加图片的位置调用productservice完成添加商品操作重定向到所有的商品的上面 fileUpload使用创建一个磁盘文件项工厂DiskFileItemFactory factory = new DiskFileItemFactory();创建一个核心文件上传对象 ServletFileUpLoadServletFileUpload upload = new ServletFileUpload(factory);上传对象调用方法解析请求 获取一个List<FileItem>List<FileItem> list = upload.parseRequest(request);遍历list获取每一个文件项isFormFiled():判断是否是普通上传组件true:普通上传组件false:文件上传组件getFiledName():获取表单子标签的name属性值若是普通的上传组件getString("utf-8"):获取用户输入的值若是文件上传组件getName():获取上传文件的名称getInputStream():获取上传文件流最后删除临时文件delete()
导入fileupload的jar包
http://pan.baidu.com/s/1jIb11gq
/store/WebContent/admin/product/list.jsp
/store/src/com/louis/web/servlet/AdminProductServlet.java
/*** 跳转到添加商品的页面* @param request* @param response* @return* @throws Exception*/public String addUI(HttpServletRequest request, HttpServletResponse response) throws Exception {//查询所有的分类 返回listCategoryService cs=(CategoryService) BeanFactory.getBean("CategoryService");List<Category> clist = cs.findAll();//将list放入requestrequest.setAttribute("clist", clist);return "/admin/product/add.jsp";}
/store/WebContent/admin/product/add.jsp
/store/src/com/louis/web/servlet/AddProductServlet.java
package com.louis.web.servlet;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.List;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils;import com.louis.domain.Category; import com.louis.domain.Product; import com.louis.service.ProductService; import com.louis.utils.BeanFactory; import com.louis.utils.UUIDUtils; import com.louis.utils.UploadUtils;/*** Servlet implementation class AddProduct*/ public class AddProductServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {//0.创建map 放入前台传递的数据HashMap<String, Object> map = new HashMap<>();//创建磁盘文件项DiskFileItemFactory factory = new DiskFileItemFactory();//创建核心上传对象ServletFileUpload upload = new ServletFileUpload(factory);//解析requestList<FileItem> list = upload.parseRequest(request);//遍历集合for (FileItem fi : list) {//判断是否是普通的上传组件if(fi.isFormField()){//普通上传组件map.put(fi.getFieldName(),fi.getString("utf-8"));}else{//文件上传组件//获取文件名称String name = fi.getName();//获取文件的真实名称 xxxx.xxString realName = UploadUtils.getRealName(name);//获取文件的随机名称String uuidName = UploadUtils.getUUIDName(realName);//获取文件的存放路径String path = this.getServletContext().getRealPath("/products/1");//获取文件流InputStream is = fi.getInputStream();//保存图片FileOutputStream os = new FileOutputStream(new File(path, uuidName));IOUtils.copy(is, os);os.close();is.close();//删除临时文件 fi.delete();//在map中设置文件的路径map.put(fi.getFieldName(), "products/1/"+uuidName);}}//1.封装参数Product p = new Product();BeanUtils.populate(p, map);//1.1 商品id p.setPid(UUIDUtils.getId());//1.2 商品时间p.setPdate(new Date());//1.3 封装cateogryCategory c = new Category();c.setCid((String)map.get("cid"));p.setCategory(c);//2.调用service完成添加ProductService ps=(ProductService) BeanFactory.getBean("ProductService");ps.add(p);//3.页面重定向response.sendRedirect(request.getContextPath()+"/adminProduct?method=findAll");} catch (Exception e) {e.printStackTrace();request.setAttribute("msg", "商品添加失败~");request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);return;}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);}}
/store/WebContent/WEB-INF/web.xml
<servlet><description></description><display-name>AddProductServlet</display-name><servlet-name>AddProductServlet</servlet-name><servlet-class>com.louis.web.servlet.AddProductServlet</servlet-class></servlet><servlet-mapping><servlet-name>AddProductServlet</servlet-name><url-pattern>/addProduct</url-pattern></servlet-mapping>
/store/src/com/louis/service/impl/ProductServiceImpl.java
/*** 添加商品*/@Overridepublic void add(Product p) throws Exception {ProductDao pdao=(ProductDao) BeanFactory.getBean("ProductDao");pdao.add(p);}
/store/src/com/louis/dao/impl/ProductDaoImpl.java
/*** 添加商品*/@Overridepublic void add(Product p) throws Exception {QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());/*** `pid` VARCHAR(32) NOT NULL,`pname` VARCHAR(50) DEFAULT NULL,`market_price` DOUBLE DEFAULT NULL,`shop_price` DOUBLE DEFAULT NULL,`pimage` VARCHAR(200) DEFAULT NULL,`pdate` DATE DEFAULT NULL,`is_hot` INT(11) DEFAULT NULL,`pdesc` VARCHAR(255) DEFAULT NULL,`pflag` INT(11) DEFAULT NULL,`cid` VARCHAR(32) DEFAULT NULL,*/String sql="insert into product values(?,?,?,?,?,?,?,?,?,?);";qr.update(sql, p.getPid(),p.getPname(),p.getMarket_price(),p.getShop_price(),p.getPimage(),p.getPdate(),p.getIs_hot(),p.getPdesc(),p.getPflag(),p.getCategory().getCid());}
问题:
beanutils
uploadfile
map
posted on 2017-10-16 11:55 Michael2397 阅读(...) 评论(...) 编辑 收藏