1 编写 新增商品 和 查询商品的页面
2 使用Servlet + JDBC 完成新增商品 和查询商品的功能
3 实现新增商品之后 重定向到 查询商品的页面
public class ProductDao {
//查询所有商品
public List findAllProduct() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.dataSource);
String sql = "select * from product";
List productList = qr.query(sql, new BeanListHandler(Product.class));
return productList;
}
//插入新的商品
public int addProduct(Product product) throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.dataSource);
String sql = "insert into product values(?,?,?,?,?,?)";
int i = qr.update(sql, product.getPid(), product.getPname(), product.getPrice(), product.getPdesc(), product.getPflag()
, product.getCid());
return i;
}
}
2.主页前端页面
主页
插入数据
3.新增数据前端页面
插入数据
返回主页
4.新增商品功能
@WebServlet(name = "addProductServlet",urlPatterns = "/addProduct")
public class AddProductServlet extends HttpServlet {
private ProductDao productDao = new ProductDao();
private Product product = new Product();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
req.setCharacterEncoding("utf-8");
String pid = req.getParameter("pid");
product.setPid(pid);
String pname = req.getParameter("pname");
product.setPname(pname);
String price = req.getParameter("price");
product.setPrice(price);
String pdesc = req.getParameter("pdesc");
product.setPdesc(pdesc);
String pflag = req.getParameter("pflag");
product.setPflag(pflag);
String cid = req.getParameter("cid");
product.setCid(cid);
int i = productDao.addProduct(product);
if (i>0){
System.out.println("数据插入成功");
resp.sendRedirect("findAllProduct.html");
} else {
System.out.println("数据插入失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.查询商品页面
查询数据
查询数据
返回插入页面
返回主页
6.查询商品功能
@WebServlet(name = "findAllProductServlet",urlPatterns = "/findAllProduct")
public class FindAllProductServlet extends HttpServlet {
//由于需要访问ProductDao中的方法,所以将其作为成员变量
private ProductDao productDao = new ProductDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//执行查询所有商品的操作
List allProduct = null;
try {
allProduct = productDao.findAllProduct();
//将allProduct集合写出到页面上
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.println("");
for (Product p :
allProduct) {
writer.println(""+p.getPname()+" "+p.getPrice()+" "+p.getPdesc()+" ");
}
writer.println("
");
} catch (SQLException e) {
e.printStackTrace();
}
}
}



