管理员——商品管理

1 查询所有商品

  1. 修改商品管理链接
d.add('010401','0104','商品管理','${pageContext.request.contextPath}/adminProductServlet?method=findAllProductsWithPage&num=1&pflag=0','','mainFrame');
  1. 添加findAllProductsWithPage方法
public String findAllProductsWithPage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    //获取当前页
    int curNum = Integer.parseInt(req.getParameter("num"));
    int pflag = Integer.parseInt(req.getParameter("pflag"));
    //调用业务层查全部商品信息返回PageModel
    ProductService productService = new ProductServiceImp();
    PageModel pm = productService.findAllProductsWithPage(pflag, curNum);
    //将PageModel放入request
    req.setAttribute("page", pm);
    //转发到/admin/product/list.jsp
    if (pflag == 0)
        return "/admin/product/list.jsp";
    else
        return "/admin/product/pushDown_list.jsp";
}
  1. 编写业务层
public PageModel findAllProductsWithPage(int pflag, int curNum) throws Exception {
    
    
    //1_创建对象
    int totalRecords = productDao.findTotalRecords(pflag);
    PageModel pm = new PageModel(curNum, totalRecords, 5);
    //2_关联集合 select * from where pflag=? product limit ? , ?
    List<Product> list = productDao.findAllProductsWithPage(pflag, pm.getStartIndex(), pm.getPageSize());
    pm.setList(list);
    //3_关联url
    pm.setUrl("adminProductServlet?method=findAllProductsWithPage&pflag="+pflag);
    return pm;
}
  1. 编写dao层
//查询商品总数
public int findTotalRecords(int pflag) {
    
    
    String sql="select count(*) from product where pflag=?";
    return template.queryForObject(sql, Integer.class, pflag);
}
//分页查询所有商品
public List<Product> findAllProductsWithPage(int pflag, int startIndex, int pageSize) {
    
    
    String sql = "select * from product where pflag=? order by pdate desc limit  ? , ?";
    return template.query(sql, new BeanPropertyRowMapper<>(Product.class), pflag, startIndex, pageSize);
}
  1. 编写/admin/product/list.jsp页面
<form id="Form1" name="Form1" action="${pageContext.request.contextPath}/admin/product/list.jsp" method="post">
    <table cellSpacing="1" cellPadding="0" width="100%" align="center" bgColor="#f5fafe" border="0">
        <TBODY>
            <tr>
                <td class="ta_01" align="center" bgColor="#afd1f3">
                    <strong>商品列表</strong>
                </TD>
            </tr>
            <tr>
                <td class="ta_01" align="right">
                    <button type="button" id="add" name="add" value="添加" class="button_add" onclick="addProduct()">&#28155;&#21152;</button>
                </td>
            </tr>
            <tr>
                <td class="ta_01" align="center" bgColor="#f5fafe">
                    <table cellspacing="0" cellpadding="1" rules="all"
                        bordercolor="gray" border="1" id="DataGrid1"
                        style="BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; WIDTH: 100%; WORD-BREAK: break-all; BORDER-BOTTOM: gray 1px solid; BORDER-COLLAPSE: collapse; BACKGROUND-COLOR: #f5fafe; WORD-WRAP: break-word">
                        <tr
                            style="FONT-WEIGHT: bold; FONT-SIZE: 12pt; HEIGHT: 25px; BACKGROUND-COLOR: #afd1f3">

                            <td align="center" width="18%">
                                序号
                            </td>
                            <td align="center" width="17%">
                                商品图片
                            </td>
                            <td align="center" width="17%">
                                商品名称
                            </td>
                            <td align="center" width="17%">
                                商品价格
                            </td>
                            <td align="center" width="17%">(1)/(0)热门
                            </td>
                            <td width="7%" align="center">
                                编辑
                            </td>
                            <td width="7%" align="center">
                                下架
                            </td>
                        </tr>
                        <c:forEach items="${page.list}" var="p" varStatus="status">
                                <tr onmouseover="this.style.backgroundColor = 'white'"
                                    onmouseout="this.style.backgroundColor = '#F5FAFE';">
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="18%">
                                        ${
    
     status.count }
                                    </td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">
                                        <img width="40" height="45" src="${ pageContext.request.contextPath }/${p.pimage}">
                                    </td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">
                                        ${
    
     p.pname }
                                    </td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">
                                        ${
    
     p.shop_price }
                                    </td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">
                                            ${
    
    p.is_hot}
                                    </td>
                                    <td align="center" style="HEIGHT: 22px">
                                        <a href="${pageContext.request.contextPath}/adminProductServlet?method=editProductUI&pid=${p.pid}">
                                            <img src="${pageContext.request.contextPath}/img/admin/i_edit.gif" border="0" style="CURSOR: hand">
                                        </a>
                                    </td>
                            
                                    <td align="center" style="HEIGHT: 22px">
                                        <%--下架 pushdown --%>
                                        <a href="${pageContext.request.contextPath}/">
                                            <img src="${pageContext.request.contextPath}/img/admin/i_del.gif" width="16" height="16" border="0" style="CURSOR: hand">
                                        </a>
                                    </td>
                                </tr>
                        </c:forEach>
                    </table>
                </td>
            </tr>
        </TBODY>
    </table>
    <%@include file="/jsp/pageFile.jsp" %>
</form>

2 添加商品(重点)

  1. 修改添加链接
<td class="ta_01" align="right">
    <button type="button" id="add" name="add" value="添加" class="button_add" onclick="addProduct()">&#28155;&#21152;</button>
</td>
<script type="text/javascript">
    function addProduct(){
    
    
        window.location.href = "${pageContext.request.contextPath}/adminProductServlet?method=addProductUI";
    }
</script>
  1. 添加addProduct方法
//addProductUI
public String addProductUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    CategoryService CategoryService = new CategoryServiceImp();
    //获取全部分类信息
    List<Category> list = CategoryService.findAllCats();
    //将全部分类信息放入request
    req.setAttribute("allCats", list);
    //转发到/admin/product/add.jsp
    return "/admin/product/add.jsp";
}

//addProduct
public String addProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    //存储表单中数据
    Map<String, String> map = new HashMap<String, String>();
    //携带表单中的数据向servcie,dao
    Product product = new Product();
    try {
    
    
        //利用req.getInputStream();获取到请求体中全部数据,进行拆分和封装
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        List<FileItem> list = upload.parseRequest(req);
        //4_遍历集合
        for (FileItem item : list) {
    
    
            if (item.isFormField()) {
    
    
                //5_如果当前的FileItem对象是普通项
                //将普通项上name属性的值作为键,将获取到的内容作为值,放入MAP中
                // {username<==>tom,password<==>1234}
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
    
    
                //6_如果当前的FileItem对象是上传项

                //获取到原始的文件名称
                String oldFileName = item.getName();
                //获取到要保存文件的名称   1222.doc  123421342143214.doc
                String newFileName = UploadUtils.getUUIDName(oldFileName);

                //通过FileItem获取到输入流对象,通过输入流可以获取到图片二进制数据
                InputStream is = item.getInputStream();
                //获取到当前项目下products/3下的真实路径
                //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3
                String realPath = getServletContext().getRealPath("/products/3/");
                String dir = UploadUtils.getDir(newFileName); // /f/e/d/c/4/9/8/4
                String path = realPath + dir; //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3/f/e/d/c/4/9/8/4
                //内存中声明一个目录
                File newDir = new File(path);
                if (!newDir.exists()) {
    
    
                    newDir.mkdirs();
                }
                //在服务端创建一个空文件(后缀必须和上传到服务端的文件名后缀一致)
                File finalFile = new File(newDir, newFileName);
                if (!finalFile.exists()) {
    
    
                    finalFile.createNewFile();
                }
                //建立和空文件对应的输出流
                OutputStream os = new FileOutputStream(finalFile);
                //将输入流中的数据刷到输出流中
                IOUtils.copy(is, os);
                //释放资源
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                //向map中存入一个键值对的数据 userhead<===> /image/11.bmp
                // {username<==>tom,password<==>1234,userhead<===>image/11.bmp}
                map.put("pimage", "/products/3/" + dir + "/" + newFileName);
            }
        }


        //7_利用BeanUtils将MAP中的数据填充到Product对象上
        BeanUtils.populate(product, map);
        product.setPid(UUIDUtils.getId());
        product.setPdate(new Date());
        product.setPflag(0);

        //8_调用servcie_dao将user上携带的数据存入数据仓库,重定向到查询全部商品信息路径
        ProductService ProductService = new ProductServiceImp();
        ProductService.saveProduct(product);

        resp.sendRedirect(req.getContextPath() + "/adminProductServlet?method=findAllProductsWithPage&num=1");

    } catch (Exception e) {
    
    
        e.printStackTrace();
    }

    return null;
}
  1. 业务层,保存商品信息
public void saveProduct(Product product) throws Exception {
    
    
    productDao.saveProduct(product);
}
  1. dao层,更新商品表,添加商品
public void saveProduct(Product product) {
    
    
    String sql="INSERT INTO product VALUES(?,?,?,?,?,?,?,?,?,?)";
    Object[] params={
    
    product.getPid(),product.getPname(),product.getMarket_price(),product.getShop_price(),product.getPimage(),product.getPdate(),product.getIs_hot(),product.getPdesc(),product.getPflag(),product.getCid()};
    template.update(sql,params);
}

3 编辑商品

  1. 修改编辑链接
<td align="center" style="HEIGHT: 22px">
    <a href="${pageContext.request.contextPath}/adminProductServlet?method=editProductUI&pid=${p.pid}">
        <img src="${pageContext.request.contextPath}/img/admin/i_edit.gif" border="0" style="CURSOR: hand">
    </a>
</td>
  1. 转发到编辑页面
public String editProductUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    String pid = req.getParameter("pid");
    req.setAttribute("pid",pid);
    CategoryService CategoryService = new CategoryServiceImp();
    //获取全部分类信息
    List<Category> list = CategoryService.findAllCats();
    //将全部分类信息放入request
    req.setAttribute("allCats", list);
    //转发到/admin/product/add.jsp
    return "/admin/product/edit.jsp";
}
  1. 编写/admin/product/edit.jsp页面
<form id="userAction_save_do" name="Form1" action="${pageContext.request.contextPath}/adminProductServlet?method=editProduct&pid=${requestScope.pid}" method="post" enctype="multipart/form-data">
	&nbsp;
	<table cellSpacing="1" cellPadding="5" width="100%" align="center" bgColor="#eeeeee" style="border: 1px solid #8ba7e3" border="0">
		<tr>
			<td class="ta_01" align="center" bgColor="#afd1f3" colSpan="4"
				height="26">
				<STRONG>编辑商品</STRONG>
			</td>
		</tr>

		<tr>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				商品名称:
			</td>
			<td class="ta_01" bgColor="#ffffff">
				<input type="text" name="pname" value="" id="pname" class="bg"/>
			</td>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				是否热门:
			</td>
			<td class="ta_01" bgColor="#ffffff">
				<select name="is_hot">
					<option value="1"></option>
					<option value="0"></option>
				</select>
			</td>
		</tr>
		<tr>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				市场价格:
			</td>
			<td class="ta_01" bgColor="#ffffff">
				<input type="text" name="market_price" value="" id="market_price" class="bg"/>
			</td>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				商城价格:
			</td>
			<td class="ta_01" bgColor="#ffffff">
				<input type="text" name="shop_price" value="" id="shop_price" class="bg"/>
			</td>
		</tr>
		<tr>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				商品图片:
			</td>
			<td class="ta_01" bgColor="#ffffff" colspan="3">
				<input type="file" name="pimage" />
			</td>
		</tr>
		<tr>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				所属的分类:
			</td>
			<td class="ta_01" bgColor="#ffffff" colspan="3">
				<select name="cid">
					<option value="">请选择</option>
					<c:forEach items="${allCats}" var="c">
						<option value="${c.cid}">${
    
    c.cname }</option>
					</c:forEach>
				</select>
			</td>
		</tr>
		<tr>
			<td width="18%" align="center" bgColor="#f5fafe" class="ta_01">
				商品描述:
			</td>
			<td class="ta_01" bgColor="#ffffff" colspan="3">
				<textarea name="pdesc" rows="5" cols="30"></textarea>
			</td>
		</tr>
		<tr>
			<td class="ta_01" style="WIDTH: 100%" align="center"
				bgColor="#f5fafe" colSpan="4">
				<button type="submit" id="userAction_save_do_submit" value="确定" class="button_ok">
					&#30830;&#23450;
				</button>

				<span style="font-family: 宋体; ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
				<button type="reset" value="重置" class="button_cancel">&#37325;&#32622;</button>

				<span style="font-family: 宋体; ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
				<INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回"/>
				<span id="Label1"></span>
			</td>
		</tr>
	</table>
</form>
  1. 添加editProduct方法
public String editProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    //存储表单中数据
    Map<String, String> map = new HashMap<>();
    //携带表单中的数据向servcie,dao
    Product product = new Product();
    try {
    
    
        //利用req.getInputStream();获取到请求体中全部数据,进行拆分和封装
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        List<FileItem> list = upload.parseRequest(req);
        //4_遍历集合
        for (FileItem item : list) {
    
    
            if (item.isFormField()) {
    
    
                //5_如果当前的FileItem对象是普通项
                //将普通项上name属性的值作为键,将获取到的内容作为值,放入MAP中
                // {username<==>tom,password<==>1234}
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
    
    
                //6_如果当前的FileItem对象是上传项

                //获取到原始的文件名称
                String oldFileName = item.getName();
                //获取到要保存文件的名称   1222.doc  123421342143214.doc
                String newFileName = UploadUtils.getUUIDName(oldFileName);

                //通过FileItem获取到输入流对象,通过输入流可以获取到图片二进制数据
                InputStream is = item.getInputStream();
                //获取到当前项目下products/3下的真实路径
                //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3
                String realPath = getServletContext().getRealPath("/products/3/");
                String dir = UploadUtils.getDir(newFileName); // /f/e/d/c/4/9/8/4
                String path = realPath + dir; //D:\tomcat\tomcat71_sz07\webapps\store_v5\products\3/f/e/d/c/4/9/8/4
                //内存中声明一个目录
                File newDir = new File(path);
                if (!newDir.exists()) {
    
    
                    newDir.mkdirs();
                }
                //在服务端创建一个空文件(后缀必须和上传到服务端的文件名后缀一致)
                File finalFile = new File(newDir, newFileName);
                if (!finalFile.exists()) {
    
    
                    finalFile.createNewFile();
                }
                //建立和空文件对应的输出流
                OutputStream os = new FileOutputStream(finalFile);
                //将输入流中的数据刷到输出流中
                IOUtils.copy(is, os);
                //释放资源
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                //向map中存入一个键值对的数据 userhead<===> /image/11.bmp
                // {username<==>tom,password<==>1234,userhead<===>image/11.bmp}
                map.put("pimage", "/products/3/" + dir + "/" + newFileName);
            }
        }
        //7_利用BeanUtils将MAP中的数据填充到Product对象上
        BeanUtils.populate(product, map);
        product.setPdate(new Date());
        String pid = req.getParameter("pid");
        product.setPid(pid);
        //8_调用servcie_dao将user上携带的数据存入数据仓库,重定向到查询全部商品信息路径
        ProductService ProductService = new ProductServiceImp();
        ProductService.editProduct(product);

        resp.sendRedirect(req.getContextPath() + "/adminProductServlet?method=findAllProductsWithPage&num=1&pflag=0");


    } catch (Exception e) {
    
    
        e.printStackTrace();
    }
    return null;
}
  1. 编写业务层
public void editProduct(Product product) throws Exception {
    
    
    productDao.editProduct(product);
}
  1. 编写dao层
public void editProduct(Product product) throws Exception {
    
    
    String sql = "UPDATE product SET pname=?, market_price=?, shop_price=?, pimage=?, pdate=?, is_hot=?, pdesc=?, cid=? where pid=?";
    Object[] params = {
    
    product.getPname(), product.getMarket_price(), product.getShop_price(), product.getPimage(), product.getPdate(), product.getIs_hot(), product.getPdesc(), product.getCid(), product.getPid()};
    template.update(sql, params);
}

4 下架商品

  1. 修改链接
<td align="center" style="HEIGHT: 22px">
    <%--下架 pushdown --%>
    <a href="${pageContext.request.contextPath}/adminProductServlet?method=pushDownOrUpProduct&pflag=1&pid=${p.pid}">
        <img src="${pageContext.request.contextPath}/img/admin/i_del.gif" width="16" height="16" border="0" style="CURSOR: hand">
    </a>
</td>
  1. 编写pushDownOrUpProduct方法
//pflag=1下架,pflag=0上架
//注意重定向时对应pflag=0,pflag=1
public String pushDownOrUpProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    
    
    String pid = req.getParameter("pid");
    int pflag = Integer.parseInt(req.getParameter("pflag"));
    ProductService productService = new ProductServiceImp();
    productService.pushDownORUpProduct(pflag, pid);
    resp.sendRedirect(req.getContextPath() + "/adminProductServlet?method=findAllProductsWithPage&num=1&pflag=" + (1 - pflag));
    return null;
}
  1. 编写业务层
public void pushDownORUpProduct(int pflag, String pid) throws Exception {
    
    
    productDao.pushDownORUpProduct(pflag, pid);
}
  1. 编写dao层
public void pushDownORUpProduct(int pflag, String pid) throws Exception {
    
    
    String sql = "UPDATE product SET pflag =? WHERE pid =?";
    template.update(sql, pflag, pid);
}

5以下架商品管理

  1. 修改链接
d.add('010402','0104','已下架商品管理','${pageContext.request.contextPath}/adminProductServlet?method=findAllProductsWithPage&num=1&pflag=1','','mainFrame');
  1. 上架商品
<td align="center" style="HEIGHT: 22px">
    <a href="${pageContext.request.contextPath}/adminProductServlet?method=pushDownOrUpProduct&pflag=0&pid=${p.pid}">
        <img src="${pageContext.request.contextPath}/img/admin/i_edit.gif" border="0" style="CURSOR: hand">
    </a>
</td>

猜你喜欢

转载自blog.csdn.net/qq_40857365/article/details/111193778
今日推荐