案例2-添加商品

1 页面一加载就能动态的获取所有的分类

案例需求图

 

1 创建category表

CREATE TABLE category (
  cid   VARCHAR(50) NOT NULL,
  cname VARCHAR(20) DEFAULT NULL,
  PRIMARY KEY (cid)
)

2 category表中添加数据

INSERT INTO category VALUES 
('1','手机数码'),('2','运动户外'),
('3','电脑办公'),('4','家具家居'),
('5','鞋靴箱包'),('6','图书音像'),
('7','母婴孕婴'),('8','汽车用品');
View Code

3admin/product/list.jsp添加处理servlet

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<HTML>
<HEAD>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="${pageContext.request.contextPath}/css/Style1.css"
    rel="stylesheet" type="text/css" />
<script language="javascript"
    src="${pageContext.request.contextPath}/js/public.js"></script>
<script type="text/javascript">
            function addProduct(){
                window.location.href = "${pageContext.request.contextPath}/adminAddProductUI";
            }
        </script>
</HEAD>
<body>
    <br>
    <form id="Form1" name="Form1"
        action="${pageContext.request.contextPath}/user/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()">
                            添加</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%">是否热门</td>
                                <td width="7%" align="center">编辑</td>
                                <td width="7%" align="center">删除</td>
                            </tr>
                            <!-- varStatus 记录第几次遍历 -->
                            <c:forEach items="${productList }" var="product" varStatus="vs">
                            
                                <tr onmouseover="this.style.backgroundColor = 'white'"
                                    onmouseout="this.style.backgroundColor = '#F5FAFE';">
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="18%">${vs.count }</td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%"><img width="40" height="45" src="${pageContext.request.contextPath }/${product.pimage }"></td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">${product.pname }</td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">${product.shop_price }</td>
                                    <td style="CURSOR: hand; HEIGHT: 22px" align="center"
                                        width="17%">
                                        ${product.is_hot==1?"是":"否" }</td>
                                    <td align="center" style="HEIGHT: 22px"><a
                                        href="${ pageContext.request.contextPath }/admin/product/edit.jsp">
                                            <img
                                            src="${pageContext.request.contextPath}/images/i_edit.gif"
                                            border="0" style="CURSOR: hand">
                                    </a></td>
        
                                    <td align="center" style="HEIGHT: 22px"><a href="#"> <img
                                            src="${pageContext.request.contextPath}/images/i_del.gif"
                                            width="16" height="16" border="0" style="CURSOR: hand">
                                    </a></td>
                                </tr>
                            </c:forEach>
                        </table>
                    </td>
                </tr>

            </TBODY>
        </table>
    </form>
</body>
</HTML>

4 web层 AdminAddProductUIServlet

package www.test.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import www.test.domain.Category;
import www.test.service.AdminProductService;

public class AdminAddProductUIServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获得所有的商品的类别数据
         AdminProductService service = new AdminProductService();
         List<Category> categoryList = null;
         try {
            categoryList =  service.findAllCategory();
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        // 将获取到的categoryList存储到request域中
         request.setAttribute("categoryList", categoryList);
           //转发
         request.getRequestDispatcher("/admin/product/add.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

5 service层AdminProductService

package www.test.service;

import java.sql.SQLException;
import java.util.List;

import www.test.dao.AdminProductDao;
import www.test.domain.Category;
import www.test.domain.Product;

public class AdminProductService {

    public List<Product> findAllProduct() throws SQLException {

         //因为没有复杂业务 直接传递请求到dao层
        AdminProductDao dao = new AdminProductDao();
        return dao.findAllProduct();
    }

    
    public List<Category> findAllCategory() throws SQLException {
        
        AdminProductDao dao = new AdminProductDao();
        return dao.finAllCategory();
         
    }

}

6 dao层AdminProductDao

package www.test.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import www.test.domain.Category;
import www.test.domain.Product;
import www.test.utils.C3P0Utils;

public class AdminProductDao {

    public List<Product> findAllProduct() throws SQLException {
        
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from product";
        List<Product> productList = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return productList;
    }

    public List<Category> finAllCategory() throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from category";
        List<Category> categoryList = qr.query(sql, new BeanListHandler<Category>(Category.class));
        return categoryList;
    }

    
}

7 /admin/product/add.jsp代码

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<HTML>
    <HEAD>
        <meta http-equiv="Content-Language" content="zh-cn">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <LINK href="${pageContext.request.contextPath}/css/Style1.css" type="text/css" rel="stylesheet">
    </HEAD>
    
    <body>
        <!--  -->
        <form id="userAction_save_do" name="Form1" action="${pageContext.request.contextPath}/adminAddProductUI" method="post">
            &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>添加商品</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="userAction_save_do_logonName" 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="userAction_save_do_logonName" 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="userAction_save_do_logonName" 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">
                            <c:forEach items="${categoryList }" var="category">
                                    <option value="${category.cid }">${category.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">
                            确认;
                        </button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</FONT>
                        <button type="reset" value="重置" class="button_cancel">重置</button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</FONT>
                        <INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回"/>
                        <span id="Label1"></span>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</HTML>

 2 添加商品

1 给确认按钮所在表单的form添加servlet

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<HTML>
    <HEAD>
        <meta http-equiv="Content-Language" content="zh-cn">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <LINK href="${pageContext.request.contextPath}/css/Style1.css" type="text/css" rel="stylesheet">
    </HEAD>
    
    <body>
        <!--  -->
        <form id="userAction_save_do" name="Form1" action="${pageContext.request.contextPath}/adminAddProduct" method="post">
            &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>添加商品</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="userAction_save_do_logonName" 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="userAction_save_do_logonName" 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="userAction_save_do_logonName" 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">
                            <c:forEach items="${categoryList }" var="category">
                                    <option value="${category.cid }">${category.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">
                            确认;
                        </button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</FONT>
                        <button type="reset" value="重置" class="button_cancel">重置</button>

                        <FONT face="宋体">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</FONT>
                        <INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回"/>
                        <div>${isSuccess==true?"添加成功":"添加失败" }</div>
                        <span id="Label1"></span>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</HTML>

2 web层AdminProductService

package www.test.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

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 www.test.domain.Product;
import www.test.service.AdminProductService;

public class AdminAddProductServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        //获取数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //使用BeanUtils进行子映射封装
        Product  product = new Product();
        try {
            BeanUtils.populate(product, parameterMap);
        } catch (IllegalAccessException | InvocationTargetException e) {
            
            e.printStackTrace();
        }
        //此位置Product已经封装完毕----将表单的数据封装完毕
        //手动设置表单中没有数据
        //1)private String pid;
        product.setPid(UUID.randomUUID().toString().replaceAll("-", ""));
        //2)private String pimage;
        product.setPimage("products/1/c_0033.jpg");
       //3)private String pdate;//上架日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String pdate = format.format(new Date());
        product.setPdate(pdate);
        //4)private int pflag;//商品是否下载 0代表未下架
        product.setPflag(0);
       
        // 3 传递数据给service层
        AdminProductService service = new AdminProductService();
        boolean isSuccess = true;
        try {
            isSuccess = service.addProduct(product);
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
        //将处理结果存储到request域中
        request.setAttribute("isSuccess", isSuccess);
         //跳转到列表页面
        //response.sendRedirect(request.getContextPath()+"/adminProductList");
        request.getRequestDispatcher("admin/product/add.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3 service层AdminProductService

package www.test.service;

import java.sql.SQLException;
import java.util.List;

import www.test.dao.AdminProductDao;
import www.test.domain.Category;
import www.test.domain.Product;

public class AdminProductService {

    public List<Product> findAllProduct() throws SQLException {

         //因为没有复杂业务 直接传递请求到dao层
        AdminProductDao dao = new AdminProductDao();
        return dao.findAllProduct();
    }

    
    public List<Category> findAllCategory() throws SQLException {
        
        AdminProductDao dao = new AdminProductDao();
        return dao.finAllCategory();
         
    }


    // 添加商品
    public boolean addProduct(Product product) throws SQLException {
        AdminProductDao dao = new AdminProductDao();
        return dao.addProduct(product);
    } 

}

4 dao层AdminProductDao

package www.test.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import www.test.domain.Category;
import www.test.domain.Product;
import www.test.utils.C3P0Utils;

public class AdminProductDao {

    public List<Product> findAllProduct() throws SQLException {
        
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from product";
        List<Product> productList = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return productList;
    }

    public List<Category> finAllCategory() throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from category";
        List<Category> categoryList = qr.query(sql, new BeanListHandler<Category>(Category.class));
        return categoryList;
    }

    //添加数据
    public boolean addProduct(Product product) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        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()};
        int num = qr.update(sql, params);
        if(num>0){
            return true;
        }else{
            return false;
        }
        
    }

    
}

 

posted @ 2018-01-24 17:11  Jepson6669  阅读(301)  评论(0编辑  收藏  举报