一、web阶段通用流程【同步操作】
- 创建数据库表结构,并创建数据库表(初始化数据)
- 根据创建的数据库表结构创建对应的JavaBean
- 导入相关的jar包,工具类和配置文件()
- 寻找程序的入口(一般在jsp页面,他会指向一个servlet,需要注意一个问题:携带参数的问题)
- 编写对应的servlet
- 如果携带了请求参数,需要获取请求参数,并封装到对应的JavaBean
- 调用service层方法
- 编写service层方法
- web阶段,除了分页和事务操作,这个类中仅仅知识调用DAO层的方法
- 编写dao层方法
- 对数据库的CRUD操作
二、功能模块
1.查询所有商品信息
web层
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import com.itheima.service.impl.ProductServiceImpl;
/**
* 查询所有商品信息
*
*/
public class FindAllProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FindAllProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ProductService service = new ProductServiceImpl();
try {
// 1.调用service层方法
List<Product> products = service.findAllProduct();
// 2.将查询结果返回域对象
request.setAttribute("products", products);
// 3.转发到jsp页面
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
service层
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.dao.impl.ProductDaoImpl;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServiceImpl implements ProductService {
private ProductDao dao = new ProductDaoImpl();
@Override
public List<Product> findAllProduct()throws Exception {
return dao.findAllProduct();
}
}
dao层
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAllProduct() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pflag=?";
// 3.设置实际参数
Object[] params = {0};
// 4.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class),params);
}
}
JSP页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>商品列表</th>
</tr>
</table>
<hr/>
<table border="1" width="100%" class="imagetable">
<tr>
<th colspan="5" align="right">
<input type="button" value="添加商品"/>
</th>
</tr>
<tr>
<th style="width:110px">商品序号</th>
<th>商品名称</th>
<th style="width:110px">商品图片</th>
<th style="width:110px">商品价格</th>
<th>商品描述</th>
</tr>
<!-- 遍历商品信息 -->
<c:if test="${not empty products }">
<c:forEach items="${products }" var="product" varStatus="vs">
<tr>
<td align="center">${vs.count }</td>
<td>${product.pname }</td>
<td align="center">
<img src="${pageContext.request.contextPath }/${product.pimage }" width="45px" height="45px">
</td>
<td align="center">${product.shop_price }</td>
<td>${product.pdesc }</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
2.添加商品信息
2.1 回显下拉框的数据
product_list.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
<style type="text/css">
a{
text-decoration: none;
color: gray;
}
</style>
<script type="text/javascript">
function addProductUI(){
location.href="${pageContext.request.contextPath }/AddProductUIServlet";
}
</script>
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>商品列表</th>
</tr>
</table>
<hr/>
<table border="1" width="100%" class="imagetable">
<tr>
<th colspan="5" align="right">
<!-- javascript:void(0):禁用插连接 -->
<a href="javascript:void(0);" onclick="addProductUI()">添加商品</a>
</th>
</tr>
<tr>
<th style="width:110px">商品序号</th>
<th>商品名称</th>
<th style="width:110px">商品图片</th>
<th style="width:110px">商品价格</th>
<th>商品描述</th>
</tr>
<!-- 遍历商品信息 -->
<c:if test="${not empty products }">
<c:forEach items="${products }" var="product" varStatus="vs">
<tr>
<td align="center">${vs.count }</td>
<td>${product.pname }</td>
<td align="center">
<img src="${pageContext.request.contextPath }/${product.pimage }" width="45px" height="45px">
</td>
<td align="center">${product.shop_price }</td>
<td>${product.pdesc }</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
web层
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.impl.CategoryServiceImpl;
/**
* 回显添加商品界面的下拉框
*
*/
public class AddProductUIServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
CategoryService service = new CategoryServiceImpl();
try {
List<Category> categorys = service.findAllCategory();
request.setAttribute("categorys", categorys);
request.getRequestDispatcher("/addProduct.jsp").forward(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
service层
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.impl.CategoryDaoImpl;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
public class CategoryServiceImpl implements CategoryService {
private CategoryDao dao = new CategoryDaoImpl();
@Override
public List<Category> findAllCategory() throws Exception{
return dao.findAllCategory();
}
@Override
public Category findCategoryById(String cid) throws Exception{
return dao.findCategoryById(cid);
}
}
dao层
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.CategoryDao;
import com.itheima.domain.Category;
import com.itheima.utils.C3P0Utils;
public class CategoryDaoImpl implements CategoryDao {
@Override
public List<Category> findAllCategory() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from category";
// 3.执行查询操作
return qr.query(sql, new BeanListHandler<>(Category.class));
}
@Override
public Category findCategoryById(String cid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from category where cid =?";
// 3.设置实际参数
Object[] params = {cid};
// 4.执行查询操作
return qr.query(sql, new BeanHandler<>(Category.class), params);
}
}
2.2 添加商品信息
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>添加商品</th>
</tr>
</table>
<hr/>
<form action="${pageContext.request.contextPath}/AddProductServlet" method="post">
<table border="1" width="65%" class="imagetable" align="center">
<tr>
<td>商品名称</td>
<td><input type="text" name="pname"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="shop_price"/></td>
</tr>
<tr>
<td>市场价格</td>
<td><input type="text" name="market_price"/></td>
</tr>
<tr>
<td>商品图片路径</td>
<td><input type="text" name="pimage"/></td>
</tr>
<tr>
<td>是否热门</td>
<td><input type="radio" name="is_hot" value="0" checked="checked"/>不热门
<input type="radio" name="is_hot" value="1"/>热门</td>
</tr>
<tr>
<td>商品描述</td>
<td>
<textarea name="pdesc"></textarea>
</td>
</tr>
<tr>
<td>商品分类</td>
<td>
<select name="cid">
<c:if test="${not empty categorys }">
<c:forEach items="${categorys}" var="category">
<option value="${category.cid}">${category.cname }</option>
</c:forEach>
</c:if>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="添加商品"/>
</td>
</tr>
</table>
</form>
</body>
</html>
web层
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.Date;
import java.util.List;
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 com.itheima.domain.Category;
import com.itheima.domain.Product;
import com.itheima.service.CategoryService;
import com.itheima.service.ProductService;
import com.itheima.service.impl.CategoryServiceImpl;
import com.itheima.service.impl.ProductServiceImpl;
import com.itheima.utils.UUIDUtils;
/**
* 添加商品信息
*
*/
public class AddProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 1.获取用户请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
// 2.使用BeanUtils工具类封装请求参数
Product product = new Product();
try {
// 2.使用BeanUtils封装用户提交的数据
BeanUtils.populate(product, request.getParameterMap());
// 3.单独封装pid,pdate,pflag,catgegory
product.setPid(UUIDUtils.getUUID());
product.setPdate(new Date());
product.setPflag(0);// 添加商品默认为上架状态
// 获得cid
String cid = request.getParameter("cid");
// 调用service层根据cid查询分类信息
CategoryService categoryService = new CategoryServiceImpl();
Category category = categoryService.findCategoryById(cid);
product.setCategory(category);
ProductService service = new ProductServiceImpl();
// 调用service层查询所有商品信息的方法
service.addProduct(product);
// 重定向到查询所有商品信息的页面
response.sendRedirect(request.getContextPath() + "/FindAllProductServlet");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
service层
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.dao.impl.ProductDaoImpl;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServiceImpl implements ProductService {
private ProductDao dao = new ProductDaoImpl();
@Override
public List<Product> findAllProduct() throws Exception {
return dao.findAllProduct();
}
@Override
public void addProduct(Product product) throws Exception {
dao.addProduct(product);
}
}
dao层
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAllProduct() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pflag=?";
// 3.设置实际参数
Object[] params = {0};
// 4.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class),params);
}
@Override
public void addProduct(Product product) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";
// 3.设置实际参数
Object[] params = { product.getPid(), product.getPname(), product.getMarket_price(),
product.getShop_price(), product.getPimage(), product.getPdate(), product.getIs_hot(),
product.getPdesc(), product.getPflag(), product.getCategory().getCid() };
// 4.执行插入操作
qr.update(sql, params);
}
}
3.删除商品信息
页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
<style type="text/css">
a{
text-decoration: none;
color: gray;
}
</style>
<script type="text/javascript">
//添加商品信息
function addProductUI(){
location.href="${pageContext.request.contextPath }/AddProductUIServlet";
}
//删除单个商品信息
function delProduct(pid){
//alert(pid);
location.href="${pageContext.request.contextPath }/DelProductServlet?pid="+pid;
}
</script>
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>商品列表</th>
</tr>
</table>
<hr/>
<table border="1" width="100%" class="imagetable">
<tr>
<th colspan="6" align="right">
<!-- javascript:void(0):禁用插连接 -->
<a href="javascript:void(0);" onclick="addProductUI()">添加商品</a>
</th>
</tr>
<tr>
<th style="width:110px">商品序号</th>
<th>商品名称</th>
<th style="width:110px">商品图片</th>
<th style="width:110px">商品价格</th>
<th>商品描述</th>
<th style="width:110px">操作</th>
</tr>
<!-- 遍历商品信息 -->
<c:if test="${not empty products }">
<c:forEach items="${products }" var="product" varStatus="vs">
<tr>
<td align="center">${vs.count }</td>
<td>${product.pname }</td>
<td align="center">
<img src="${pageContext.request.contextPath }/${product.pimage }" width="45px" height="45px">
</td>
<td align="center">${product.shop_price }</td>
<td>${product.pdesc }</td>
<td align="center">
<a href="javascript:void(0);" onclick="delProduct('${product.pid}')">删除</a>
<a href="javascript:void(0);" onclick="">修改</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
web层
package com.itheima.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.service.ProductService;
import com.itheima.service.impl.ProductServiceImpl;
public class DelProductByIdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DelProductByIdServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取请求参数
String pid = request.getParameter("pid");
// 2.调用service层根据pid删除商品信息的方法
ProductService service = new ProductServiceImpl();
try {
service.delProductById(pid);
// 3.重定向到查询所有商品信息的Servlet
response.sendRedirect(request.getContextPath() + "/FindAllProductServlet");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
service层
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.dao.impl.ProductDaoImpl;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServiceImpl implements ProductService {
private ProductDao dao = new ProductDaoImpl();
@Override
public List<Product> findAllProduct() throws Exception {
return dao.findAllProduct();
}
@Override
public void addProduct(Product product) throws Exception {
dao.addProduct(product);
}
@Override
public void delProductById(String pid) throws Exception {
dao.delProductById(pid);
}
}
dao层
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAllProduct() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pflag=?";
// 3.设置实际参数
Object[] params = { 0 };
// 4.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class), params);
}
@Override
public void addProduct(Product product) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";
// 3.设置实际参数
Object[] params = { product.getPid(), product.getPname(), product.getMarket_price(), product.getShop_price(),
product.getPimage(), product.getPdate(), product.getIs_hot(), product.getPdesc(), product.getPflag(),
product.getCategory().getCid() };
// 4.执行插入操作
qr.update(sql, params);
}
@Override
public void delProductById(String pid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "delete from product where pid = ?";
// 3.设置实际参数
Object[] params = { pid };
// 4.执行插入操作
qr.update(sql, params);
}
}
4.修改商品信息
3.1 回显数据
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
<style type="text/css">
a{
text-decoration: none;
color: gray;
}
</style>
<script type="text/javascript">
//添加商品信息
function addProductUI(){
location.href="${pageContext.request.contextPath }/AddProductUIServlet";
}
//删除单个商品信息
function delProductByPid(pid){
//alert(pid);
location.href="${pageContext.request.contextPath }/DelProductByIdServlet?pid="+pid;
}
function modifyProductByPid(pid){
//alert(pid);
location.href="${pageContext.request.contextPath }/ModifyUIProductServlet?pid="+pid;
}
</script>
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>商品列表</th>
</tr>
</table>
<hr/>
<table border="1" width="100%" class="imagetable">
<tr>
<th colspan="6" align="right">
<!-- javascript:void(0):禁用插连接 -->
<a href="javascript:void(0);" onclick="addProductUI()">添加商品</a>
</th>
</tr>
<tr>
<th style="width:110px">商品序号</th>
<th>商品名称</th>
<th style="width:110px">商品图片</th>
<th style="width:110px">商品价格</th>
<th>商品描述</th>
<th style="width:110px">操作</th>
</tr>
<!-- 遍历商品信息 -->
<c:if test="${not empty products }">
<c:forEach items="${products }" var="product" varStatus="vs">
<tr>
<td align="center">${vs.count }</td>
<td>${product.pname }</td>
<td align="center">
<img src="${pageContext.request.contextPath }/${product.pimage }" width="45px" height="45px">
</td>
<td align="center">${product.shop_price }</td>
<td>${product.pdesc }</td>
<td align="center">
<a href="javascript:void(0);" onclick="delProductByPid('${product.pid}')">删除</a>
<a href="javascript:void(0);" onclick="modifyProductByPid('${product.pid}')">修改</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.domain.Category;
import com.itheima.domain.Product;
import com.itheima.service.CategoryService;
import com.itheima.service.ProductService;
import com.itheima.service.impl.CategoryServiceImpl;
import com.itheima.service.impl.ProductServiceImpl;
public class ModifyUIProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ModifyUIProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取请求参数
String pid = request.getParameter("pid");
//2.调用service层,根据ID查询商品信息的方法
ProductService service = new ProductServiceImpl();
try {
Product product = service.findProductByPid(pid);
//3.查询所有商品的分类信息
CategoryService categoryService = new CategoryServiceImpl();
List<Category> categorys = categoryService.findAllCategory();
//4.将查询结果保存域对象
request.setAttribute("product", product);
request.setAttribute("categorys", categorys);
//5.跳转到修改页面
request.getRequestDispatcher("/modify.jsp").forward(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.dao.impl.ProductDaoImpl;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServiceImpl implements ProductService {
private ProductDao dao = new ProductDaoImpl();
@Override
public List<Product> findAllProduct() throws Exception {
return dao.findAllProduct();
}
@Override
public void addProduct(Product product) throws Exception {
dao.addProduct(product);
}
@Override
public void delProductById(String pid) throws Exception {
dao.delProductById(pid);
}
@Override
public Product findProductByPid(String pid) throws Exception {
return dao.findProductByPid(pid);
}
}
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAllProduct() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pflag=?";
// 3.设置实际参数
Object[] params = { 0 };
// 4.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class), params);
}
@Override
public void addProduct(Product product) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";
// 3.设置实际参数
Object[] params = { product.getPid(), product.getPname(), product.getMarket_price(), product.getShop_price(),
product.getPimage(), product.getPdate(), product.getIs_hot(), product.getPdesc(), product.getPflag(),
product.getCategory().getCid() };
// 4.执行插入操作
qr.update(sql, params);
}
@Override
public void delProductById(String pid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "delete from product where pid = ?";
// 3.设置实际参数
Object[] params = { pid };
// 4.执行插入操作
qr.update(sql, params);
}
@Override
public Product findProductByPid(String pid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pid=?";
// 3.设置实际参数
Object[] params = {pid};
// 4.执行查询操作
return qr.query(sql, new BeanHandler<>(Product.class), params);
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/imagetable.css">
</head>
<body>
<table border="1" width="40%" class="imagetable" align="center">
<tr>
<th>修改商品</th>
</tr>
</table>
<hr/>
<form action="${pageContext.request.contextPath}/ModifyServlet" method="post">
<table border="1" width="65%" class="imagetable" align="center">
<tr>
<td>商品名称</td>
<td><input type="text" name="pname" value="${product.pname }"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="shop_price" value="${product.shop_price }"/></td>
</tr>
<tr>
<td>市场价格</td>
<td><input type="text" name="market_price" value="${product.market_price }"/></td>
</tr>
<tr>
<td>商品图片路径</td>
<td><input type="text" name="pimage" value="${product.pimage }"/></td>
</tr>
<tr>
<td>是否热门</td>
<td><input type="radio" name="is_hot" value="0" <c:if test="${product.is_hot==0}">checked="checkded"</c:if> />不热门
<input type="radio" name="is_hot" value="1" <c:if test="${product.is_hot==1}">checked="checkded"</c:if>/>热门</td>
</tr>
<tr>
<td>商品描述</td>
<td>
<textarea name="pdesc">${product.pdesc }</textarea>
</td>
</tr>
<tr>
<td>商品分类</td>
<td>
<select name="cid">
<c:if test="${not empty categorys }">
<c:forEach items="${categorys }" var="category">
<option value="${category.cid }" <c:if test="${category.cid==product.cid }">selected="selected"</c:if>>${category.cname }</option>
</c:forEach>
</c:if>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="修改商品"/>
</td>
</tr>
</table>
</form>
</body>
</html>
3.2 修改数据
package com.itheima.web.servlet;
import java.io.IOException;
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 com.itheima.domain.Category;
import com.itheima.domain.Product;
import com.itheima.service.CategoryService;
import com.itheima.service.ProductService;
import com.itheima.service.impl.CategoryServiceImpl;
import com.itheima.service.impl.ProductServiceImpl;
public class ModifyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ModifyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
Product product = new Product();
try {
//2.封装数据
BeanUtils.populate(product, parameterMap);
//3.调用service层根据商品ID修改商品信息的代码
ProductService service = new ProductServiceImpl();
//获得cid
String cid = request.getParameter("cid");
CategoryService categoryService = new CategoryServiceImpl();
Category category = categoryService.findCategoryById(cid);
product.setCategory(category);
service.modifyProductByPid(product);
//4.重定向到查询所有商品信息的Servlet
response.sendRedirect(request.getContextPath()+"/FindAllProductServlet");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.itheima.service.impl;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.dao.impl.ProductDaoImpl;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServiceImpl implements ProductService {
private ProductDao dao = new ProductDaoImpl();
@Override
public List<Product> findAllProduct() throws Exception {
return dao.findAllProduct();
}
@Override
public void addProduct(Product product) throws Exception {
dao.addProduct(product);
}
@Override
public void delProductById(String pid) throws Exception {
dao.delProductById(pid);
}
@Override
public Product findProductByPid(String pid) throws Exception {
return dao.findProductByPid(pid);
}
@Override
public void modifyProductByPid(Product product) throws Exception {
dao.modifyProductByPid(product);
}
}
package com.itheima.dao.impl;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAllProduct() throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pflag=?";
// 3.设置实际参数
Object[] params = { 0 };
// 4.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class), params);
}
@Override
public void addProduct(Product product) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";
// 3.设置实际参数
Object[] params = { product.getPid(), product.getPname(), product.getMarket_price(), product.getShop_price(),
product.getPimage(), product.getPdate(), product.getIs_hot(), product.getPdesc(), product.getPflag(),
product.getCategory().getCid() };
// 4.执行插入操作
qr.update(sql, params);
}
@Override
public void delProductById(String pid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "delete from product where pid = ?";
// 3.设置实际参数
Object[] params = { pid };
// 4.执行插入操作
qr.update(sql, params);
}
@Override
public Product findProductByPid(String pid) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product where pid=?";
// 3.设置实际参数
Object[] params = { pid };
// 4.执行查询操作
return qr.query(sql, new BeanHandler<>(Product.class), params);
}
@Override
public void modifyProductByPid(Product product) throws Exception {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "update product set pname=?,shop_price=?,market_price=?,pimage=?,is_hot=?,pdesc=?,cid=? where pid=?";
// 3.设置实际参数
Object[] params = { product.getPname(), product.getShop_price(), product.getMarket_price(), product.getPimage(),
product.getIs_hot(), product.getPdesc(), product.getCid(), product.getPid() };
// 4.执行更新操作
qr.update(sql, params);
}
}