商品的添加与查询

(产生随机序号的工具类):
package bull.utils;
/**
 * 随机获取序号
 */
import java.util.UUID;

public class UUIDUtils {
    public static String getUUID() {
        //生成的序号中有'-',去掉
        return UUID.randomUUID().toString().replace("-", "");
    }
}

查询所有商品

ProductDao:
public List<Product> findAll() throws SQLException {
        /**
         * 查询所有数据
         */
        QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
        String sql = "select * from product order by pdate desc";
        List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }
ProductService:
/**
     * 查询所有数据
     * @return
     * @throws SQLException
     */
    public List<Product> findAll() throws SQLException {
        ProductDao productDao = new ProductDao();
        List<Product> list = productDao.findAll();
        return list;
    }
ProductFindAllSerclet:
package bull01.Product.ProductServlet;

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 bull01.Product.ProductDomain.Product;
import bull01.Product.ProductService.ProductService;

public class ProductFindAllServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            ProductService productService = new ProductService();
            List<Product> list = productService.findAll();
            request.setAttribute("list", list);
            request.getRequestDispatcher("/product/product_list.jsp").forward(request, response);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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

}
product_list.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'product_list.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
        function addProduct() {
            window.location.href="${pageContext.request.contextPath}/product/addProduct.jsp";
        }                                                 
    </script>

  </head>

  <body>
    <table border="1px" width="800">
        <tr>
            <td colspan="7">
                商品名称:<input type="text" name="pname"><input type="button" value="查询" onclick="serach()">&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" value="添加" onclick="addProduct()">&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" value="删除" onclick="deleteProduct()">
            </td>
        </tr>
        <tr>
            <td>序号</td>
            <td>商品名称</td>
            <td>市场价格</td>
            <td>商城价格</td>
            <td>是否热门</td>
            <td>是否下架</td>
            <td>操作</td>
        </tr>
        <c:forEach var="p" items="${ list }" varStatus="status">
            <tr>
                <td>${ status.count }</td>
                <td>${ p.pname }</td>
                <td>${ p.market_price }</td>
                <td>${ p.shop_price }</td>
                <td>
                    <c:if test="${ p.is_hot == 1  }"></c:if>
                    <c:if test="${ p.is_hot == 0 }"></c:if>
                </td>
                <td>
                    <c:if test="${ p.pflag == 1 }">
                        已下架
                    </c:if>
                    <c:if test="${ p.pflag == 0 }">
                        未下架
                    </c:if>
                </td>
                <td><a href="/Web13_1/EditProductServlet?pid=${ p.pid }">修改</a>|<a href="">删除</a></td>
            </tr>
        </c:forEach>
    </table>
  </body>
</html>

关键字模糊查询

SearchProductServlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            //接收数据
            String pname = request.getParameter("pname");
            //调用业务层处理数据
            ProductService productService = new ProductService();
            List<Product> list = productService.search(pname);
            //页面跳转,将查询结果显示到product_list.jsp
            request.setAttribute("list", list);
            request.getRequestDispatcher("/product/product_list.jsp").forward(request, response);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
ProductService:
/**
     * 查找数据
     * @param pname
     * @return
     * @throws SQLException
     */
    public List<Product> search(String pname) throws SQLException {
        ProductDao productDao = new ProductDao();
        List<Product> list = productDao.search(pname);
        return list;
    }
ProductDao:
/**
     * 查询数据
     * @param pname
     * @return
     * @throws SQLException 
     */
    public List<Product> search(String pname) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.getDataSource());
        String sql = "select * from product where pname like ? order by pdate desc";
        //"%"+pname+"%" --> %pname%
        List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class), "%"+pname+"%");
        return list;

    }
js:
function search() {
            //获取文本框的值
            var pname = document.getElementById("pname").value;
            //获得表单,改变他的action属性
            document.getElementById("form1").action="${ pageContext.request.contextPath }/SearchProductServlet";
            //表单提交
            document.getElementById("form1").submit();
        }

添加商品

ProductDao:
/**
     * 添加数据
     * @param product
     * @throws SQLException
     */
    public void add(Product product) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0JDBCUtils.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()};
        queryRunner.update(sql, params);
    }
ProductService:
/**
     * 添加数据
     * @param product
     * @throws SQLException
     */
    public void add(Product product) throws SQLException {
        ProductDao productDao = new ProductDao();
        productDao.add(product);
    }
AddProductServlet:
package bull01.Product.ProductServlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

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 bull.utils.UUIDUtils;
import bull01.Product.ProductDomain.Product;
import bull01.Product.ProductService.ProductService;

public class AddProductServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        try {
            /**
             * 判断是否重复提交
             */
            //获取表单中的令牌
            String token1 = request.getParameter("token");
            //获取session中的令牌
            String token2 = (String) request.getSession().getAttribute("token");
            //先清空session中的令牌
            request.getSession().removeAttribute("token");
            //因为一次提交session中的token和表单中获取的token一样。如果两个token不同,说明提交了两次。
            if(!token1.equals(token2)) {
                request.setAttribute("msg","您已经提交过了,请不要重复提交!");
                request.getRequestDispatcher("/product/err.jsp").forward(request, response);
                return;//已经提交,直接return,不要继续往下执行。
            }


            //接收数据
            Map<String,String[]> map = request.getParameterMap();
            Product product = new Product();
            BeanUtils.populate(product, map);
            //接收的数据中没有上架时间,这里设置时间
            product.setPdate(new Date());
            //数据库中没有设置自动增长的序号,这里设置序号
            product.setPid(UUIDUtils.getUUID());

            ProductService productService = new ProductService();
            productService.add(product);
            //注意这里要跳到ProductFindAllServlet,这个Servlet再进行查询显示到product_list.jsp
            request.getRequestDispatcher("/ProductFindAllServlet").forward(request, response);

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


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

}
addProduct.jsp:
<body>
  <%
        //生成一个随机令牌
        String token = UUIDUtils.getUUID();
        //保存到session中
        session.setAttribute("token", token);
   %>
    <form action="/Web13_1/AddProductServlet" method="post">
        <!-- 隐藏令牌 -->
        <input type="hidden" value="<%=token %>" name="token">
        <table border="1px" width=500>
            <tr>
                <td>商品名称</td>
                <td><input type="text" name="pname"></td>
            </tr>
            <tr>
                <td>市场价格</td>
                <td><input type="text" name="market_price"></td>
            </tr>
            <tr>
                <td>商城价格</td>
                <td><input type="text" name="shop_price"></td>
            </tr>
            <tr>
                <td>是否热门</td>
                <td>
                <input type="radio" name="is_hot" value="1"><input type="radio" name="is_hot" value="0"></td>
            </tr>
            <tr>
                <td>是否下架</td>
                <td>
                    <select name="pflag">
                        <option value="0" selected></option>
                        <option value="1"></option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>商品描述</td>
                <td><textarea rows="10" cols="10" name="pdesc"></textarea></td>
            </tr>
            <tr>
                <td>商品分类</td>
                <td>
                    <select name="cid">
                        <option value="1">手机数码</option>
                        <option value="2">电脑办公</option>
                        <option value="3">汽车用品</option>
                        <option value="4">鞋靴箱包</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="添加"></td>
            </tr>
        </table>
    </form>
  </body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值