添加商品(上传图片) 1.修改页面上添加连接 /store/adminProduct?method=addUI 2.在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(); 创建一个核心文件上传对象 ServletFileUpLoad ServletFileUpload 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 { //查询所有的分类 返回list CategoryService cs=(CategoryService) BeanFactory.getBean("CategoryService"); List<Category> clist = cs.findAll(); //将list放入request request.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); //解析request List<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.xx String 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 封装cateogry Category 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
/** * 添加商品 */ @Override public void add(Product p) throws Exception { ProductDao pdao=(ProductDao) BeanFactory.getBean("ProductDao"); pdao.add(p); }
/store/src/com/louis/dao/impl/ProductDaoImpl.java
/** * 添加商品 */ @Override public 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