商品信息的简单增删改查

来源:互联网 发布:bluestack mac 编辑:程序博客网 时间:2024/06/11 19:49

1. 主页面

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!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></head><body><a href="${pageContext.request.contextPath }/showAll">点击查询所有商品信息</a></body></html>


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"><script type="text/javascript">function add(){location.href="${pageContext.request.contextPath}/findClist"}</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"><input type="button" value="添加商品" onclick="add()"/></th></tr><tr><th>商品序号</th><th>商品名称</th><th>商品图片</th><th>商品价格</th><th colspan="2">商品描述</th></tr><c:if test="${not empty plist}"><!--  做一个判断,防止空指针异常--><!-- 遍历设置值 --><!-- 这里是el表达式,注意!!!!!!!!!!!!!!!!!!!!!!!!!!!! --><c:forEach items="${plist }" var="product" varStatus="con"><tr><td>${con.count }</td><td>${product.pname}</td><td><img src="${pageContext.request.contextPath }/${product.pimage }" width="100%"></td><td>${product.shop_price }</td><td>${product.pdesc }</td><!--从保存在request中的product获取pid对象,并通过形参传递的方式,传过去  --><td><a href="${pageContext.request.contextPath}/update?pid=${product.pid}">修改商品</a><a href="${pageContext.request.contextPath}/delete?pid=${product.pid}">删除商品</a></td></tr></c:forEach></c:if></table></body></html>


3.添加页面

<%@ 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 }/add" method="post"><table border="1" width="100%" class="imagetable"><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="pimage" /></td></tr><tr><td>商品描述</td><td><textarea name="pdesc"></textarea></td></tr><tr><td>商品分类</td><td><select name="cid"><c:if test="${not empty clist }"><c:forEach items="${clist }" var="c"><option value=${c.cid }>${c.cname }</option></c:forEach></c:if></select></td></tr><tr><td></td><td ><input type="submit" value="添加商品"/></td></tr></table></form></body></html>


4.修改页面

<%@ 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 }/modify" method="post"><!-- 设置一个隐藏属性,将当前商品的pid信息保留下来 --><input type="hidden" name="pid" value="${product.pid}"/><table border="1" width="100%" class="imagetable"><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="pimage" value="${product.pimage }"/></td></tr><tr><td>商品描述</td><td><textarea name="pdesc">${product.pdesc }${product.pid }</textarea></td></tr><tr><td>商品分类</td><td><select name="cid"><c:if test="${not empty clist }"><c:forEach items="${clist }" var="c"><option value="${c.cid }" <c:if test="${c.cid==product.category.cid }">selected="selected"</c:if>>${c.cname }</option></c:forEach></c:if></select></td></tr><tr><td></td><td ><input type="submit" value="修改商品"/></td></tr></table></form></body></html>

5.工具类

package com.yynh.store.product.utils;import java.sql.Connection;import java.sql.SQLException;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3p0Utils {// 连接池就定义 并且加载配置完毕// 命名配置// private static DataSource dataSource=new ComboPooledDataSource("itcast");// 默认配置private static DataSource dataSource = new ComboPooledDataSource();// c3p0+DBUtils// DBUtils使用时,需要获取dataSource对象public static DataSource getDataSource() {return dataSource;}/** * 获取链接方法 */public static Connection getConnection() {Connection con = null;try {con = dataSource.getConnection();} catch (SQLException e) {e.printStackTrace();throw new RuntimeException();}return con;}public static void main(String[] args) throws SQLException {for (int i = 0; i < 40; i++) {Connection con = C3p0Utils.getConnection();System.out.println("获取到的" + con);// 不会关闭con对象,C3P0已经帮我去增强了Connection close方法con.close();}}}


package com.yynh.store.product.utils;import java.util.UUID;public class UUIDUtils {public static String getUUID() {return UUID.randomUUID().toString().replaceAll("-", "");}}



6.javaBean

package com.yynh.store.product.domain;import java.io.Serializable;public class Category implements Serializable {private String cid;private String cname;// 先创建category,作为主键public String getCid() {return cid;}public void setCid(String cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}}

package com.yynh.store.product.domain;import java.io.Serializable;import java.util.Date;public class Product implements Serializable {/** * pid varchar(32) NOT NULL,1111111111 pname varchar(50) DEFAULT NULL,1111111111 market_price double DEFAULT NULL, shop_price double DEFAULT NULL,1111111111 pimage varchar(200) DEFAULT NULL,11111111 pdate date DEFAULT NULL, 11111111 is_hot int(11) DEFAULT NULL, pdesc varchar(255) DEFAULT NULL, 11111111 pflag int(11) DEFAULT NULL, cid varchar(32) DEFAULT NULL,11111111 */private String pid;private String pname;private double shop_price;private String pimage;private Date pdate;private String pdesc;// 创建外键约束private Category Category;public Product() {super();// TODO Auto-generated constructor stub}public String getPid() {return pid;}public void setPid(String pid) {this.pid = pid;}public String getPname() {return pname;}public void setPname(String pname) {this.pname = pname;}public double getShop_price() {return shop_price;}public void setShop_price(double shop_price) {this.shop_price = shop_price;}public String getPimage() {return pimage;}public void setPimage(String pimage) {this.pimage = pimage;}public Date getPdate() {return pdate;}public void setPdate(Date pdate) {this.pdate = pdate;}public String getPdesc() {return pdesc;}public void setPdesc(String pdesc) {this.pdesc = pdesc;}public Category getCategory() {return Category;}public void setCategory(Category category) {Category = category;}@Overridepublic String toString() {return "Product [pid=" + pid + ", pname=" + pname + ", shop_price=" + shop_price + ", pimage=" + pimage + ", pdate=" + pdate + ", pdesc=" + pdesc + ", Category=" + Category + "]";}}



7.servlet

package com.yynh.store.product.servlet;import java.io.IOException;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 com.yynh.store.product.domain.Category;import com.yynh.store.product.domain.Product;import com.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;import com.yynh.store.product.utils.UUIDUtils;/** * Servlet implementation class AddProduct */public class AddProduct extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {// 添加商品功能的实现// 获取参数,封装实体// 防止乱码request.setCharacterEncoding("utf-8");Product product = new Product();Map<String, String[]> map = request.getParameterMap();// 封装数据BeanUtils.populate(product, map);// 手动封装外键Category category = new Category();String cid = request.getParameter("cid");category.setCid(cid);product.setCategory(category);// 添加pdate和pid(pid用随意字符串来当做主键)product.setPid(UUIDUtils.getUUID());product.setPdate(new Date());// 调用service方法,处理业务ProductService service = new ProductServiceIml();service.add(product);// 数据回显// 重定向到查询所有页面response.sendRedirect(request.getContextPath() + "/showAll");} catch (Exception e) {// 防止乱码response.setContentType("text/html;charset=utf-8");// 出错时显示到浏览器中response.getWriter().print("<h5>程序忙哦</h5>");}}}
package com.yynh.store.product.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.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;/** * Servlet implementation class Delete */public class Delete extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {// 获取参数,封装对象String pid = request.getParameter("pid");// 调用service处理业务ProductService service = new ProductServiceIml();service.del(pid);// 回显数据response.sendRedirect(request.getContextPath() + "/showAll");} catch (Exception e) {response.setContentType("text/html;charset=utf-8");response.getWriter().print("删除有误哦");}}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

package com.yynh.store.product.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.yynh.store.product.domain.Category;import com.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;public class FindClist extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {// 获取category的list的servlet// 没有参数// 调用service方法ProductService service = new ProductServiceIml();List<Category> clist = service.findClist();// 回显数据request.setAttribute("clist", clist);// 请求转发到添加页面request.getRequestDispatcher("/save.jsp").forward(request, response);} catch (Exception e) {// 防止乱码response.setContentType("text/html;charset=utf-8");// 出错时显示到浏览器中response.getWriter().print("<h5>程序忙哦</h5>");}}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
package com.yynh.store.product.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 org.apache.commons.beanutils.BeanUtils;import com.yynh.store.product.domain.Category;import com.yynh.store.product.domain.Product;import com.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;/** * Servlet implementation class Modify */public class Modify extends HttpServlet {private static final long serialVersionUID = 1L;/** * @see HttpServlet#HttpServlet() */public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {request.setCharacterEncoding("utf-8");// 修改提交servlet// 获取资源,封装实体// System.out.println(request.getParameter("pid"));String pid = request.getParameter("pid");Product product = new Product();BeanUtils.populate(product, request.getParameterMap());// 手动封装cidString cid = request.getParameter("cid");Category category = new Category();category.setCid(cid);product.setCategory(category);// 调用serviceProductService service = new ProductServiceIml();service.modify(product);// 回显数据// 重定向到查询所有页面response.sendRedirect(request.getContextPath() + "/showAll");} catch (Exception e) {// 防止乱码response.setContentType("text/html;charset=utf-8");// 出错时显示到浏览器中response.getWriter().print("<h5>程序忙哦</h5>");}}}


package com.yynh.store.product.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.yynh.store.product.domain.Product;import com.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;public class ShowAll extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {// 获取数据,封住实体// 调用service对象,处理业务ProductService service = new ProductServiceIml();List<Product> plist = service.showAll();// 数据回显request.setAttribute("plist", plist);// 请求转发不需要项目名System.out.println("哈哈哈");request.getRequestDispatcher("/plist.jsp").forward(request, response);} catch (Exception e) {// 防止乱码response.setContentType("text/html;charset=utf-8");// 出错时显示到浏览器中response.getWriter().print("<h5>程序忙哦</h5>");}}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}


package com.yynh.store.product.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.yynh.store.product.domain.Category;import com.yynh.store.product.domain.Product;import com.yynh.store.product.service.ProductService;import com.yynh.store.product.service.ProductServiceIml;/** * Servlet implementation class Update */public class Update extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {// 修改页面的servlet// 获取数据,封装实体// 获取超链接中保存的pidString pid = request.getParameter("pid");Product product = new Product();// 将pid封装到bean中product.setPid(pid);// 调用功能service处理ProductService service = new ProductServiceIml();// 调用功能方法,将封装好的bean传过去Product result = service.showById(product);request.setAttribute("product", result);List<Category> clist = service.findClist();// 回显数据request.setAttribute("clist", clist);// 请求转发到添加页面request.getRequestDispatcher("/update.jsp").forward(request, response);} catch (Exception e) {// 防止乱码response.setContentType("text/html;charset=utf-8");// 出错时显示到浏览器中response.getWriter().print("<h5>程序忙哦</h5>");}}}


8.service

package com.yynh.store.product.service;import java.util.List;import com.yynh.store.product.dao.ProductDao;import com.yynh.store.product.dao.ProductDaoIml;import com.yynh.store.product.domain.Category;import com.yynh.store.product.domain.Product;public class ProductServiceIml implements ProductService {/** * @author yynh_ 删除商品 */public void del(String pid) {ProductDao pd = new ProductDaoIml();pd.del(pid);}/** * @author yynh_ 修改商品信息 */public void modify(Product product) {ProductDao pd = new ProductDaoIml();pd.modify(product);}/** * @author yynh_ 根据id获取信息 */public Product showById(Product product) {ProductDao pd = new ProductDaoIml();Product p = pd.showById(product);return p;}/** * @author yynh_ 查询category的分类列表 */public List<Category> findClist() {ProductDao pd = new ProductDaoIml();List<Category> clist = pd.findClist();return clist;}/** * @author yynh_ 添加商品功能 */public void add(Product product) {ProductDao pd = new ProductDaoIml();pd.add(product);}/** * @author yynh_ 查询全部商品功能 */public List<Product> showAll() {ProductDao pd = new ProductDaoIml();List<Product> plist = pd.showAll();return plist;}}


9.dao


package com.yynh.store.product.dao;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.MapHandler;import com.yynh.store.product.domain.Category;import com.yynh.store.product.domain.Product;import com.yynh.store.product.utils.C3p0Utils;public class ProductDaoIml implements ProductDao {/** * 删除商品 */public void del(String pid) {QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());String sql = "delete from product where pid=?";Object[] param = { pid };try {run.update(sql, param);} catch (SQLException e) {e.printStackTrace();throw new RuntimeException();}}/** * 修改选中的商品信息 */public void modify(Product product) {QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());String sql = "update product set pname=?,shop_price=?,pimage=?,pdesc=?,cid=? where pid=?";Object[] param = { product.getPname(), product.getShop_price(), product.getPimage(), product.getPdesc(), product.getCategory().getCid(), product.getPid() };try {run.update(sql, param);} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}/** * 获取选中的商品信息 */@Overridepublic Product showById(Product product) {QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());String sql = "select * from product where pid=?";Object[] param = { product.getPid() };try {// 为了能获取到produt中category的分类,必须要将所有的信息都获取到Map<String, Object> map = run.query(sql, new MapHandler(), param);Category category = new Category();// 将category中的数据封装进去BeanUtils.populate(category, map);Product product2 = new Product();// 将product中需要的数据封装进去BeanUtils.populate(product2, map);// 将category作为外键封装到product中product2.setCategory(category);return product2;} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}/** * 获取category的分类信息 */public List<Category> findClist() {List<Category> result = new ArrayList<Category>();// 获取dbutilsQueryRunner run = new QueryRunner(C3p0Utils.getDataSource());String sql = "select * from category";try {result = run.query(sql, new BeanListHandler<Category>(Category.class));} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}return result;}/** * 添加商品 * */public void add(Product product) {// 获取dbutils的核心对象QueryRunner run = new QueryRunner(C3p0Utils.getDataSource());String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";// 设置属性Object[] param = { product.getPid(), product.getPname(), null, product.getShop_price(), product.getPimage(), product.getPdate(), null, product.getPdesc(), null, product.getCategory().getCid() };try {run.update(sql, param);} catch (SQLException e) {e.printStackTrace();throw new RuntimeException(e);}}public List<Product> showAll() {/** * 查询全部商品 * */List<Product> result = new ArrayList<Product>();// 获取dbutilsQueryRunner run = new QueryRunner(C3p0Utils.getDataSource());// 排序String sql = "select * from product order by pdate desc";try {result = run.query(sql, new BeanListHandler<Product>(Product.class));} catch (SQLException e) {// 将异常抛出去throw new RuntimeException(e);}return result;}}


0 0
原创粉丝点击