作业终于做完了,好开心。。。。。。虽然这一周经历不是那么顺利,但是觉得还是收获了不少,有过想哭的冲动,代码不会写,事情办不好,各种发愁。空间里发小发了带父母出去游玩的照片,瞬间能量值不知道是被击退的多还是回返的多。不过今天终于补满能量值。下面我来分享一下我的运行结果。
下面我把我管理后台的代码粘贴一下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>top.jsp</title><style type="text/css"> body {text-align: center;font-size: 38px; }* {font-family: 华文楷体;font-size: 18px;color: #F0F "; }h1 {text-align: center;font-size: 38px; } </style></head><body><h1 style="font-size: 38px;">欢迎登录网上购物后台</h1><form action="<c:url value='/AdminServlet'/>" method="post"><input type="hidden" name="method" value="1">用户名:<input type="text" name="username" /><br />密 码:<input type="password" name="password" /><br /><input type="submit" value="登录"></form></body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>list.jsp</title><style type="text/css"> body {text-align: center;font-size: 38px; }* {font-family: 华文楷体;font-size: 18px;color: #F0F "; } img{width: 50px;height: 30px;} h1 {text-align: center;font-size: 38px; }a:link {color: #999;text-decoration: none; }a:VISITED {text-decoration: none;color: #c60; }a:HOVER {text-decoration: none;color: #00F; } </style></head><body><h1 style="font-size: 38px;">欢迎登录到网上购物后台系统</h1><a style="font-size: 26px;"href="<c:url value='/AdminServlet?method=2'/>">查看商品</a><a style="font-size: 26px;" href="<c:url value='/admin/add.jsp'/>">添加商品</a><a style="font-size: 26px;"href="<c:url value='/AdminServlet?method=7'/>">查看订单</a><a style="font-size: 26px;" href="<c:url value='/admin/login.jsp'/>">退出系统</a><table border="1" align="center" width="60%"><tr><th>商品名</th><th>价格</th><th>类型</th><th>数量</th><th>图片</th><th>描述</th><th>操作</th></tr><c:forEach items="${pb.datas }" var="c"><tr><td>${c.name }</td><td>${c.price }</td><td>${c.category }</td><td>${c.pnum}</td><td><a href="<c:url value='/AdminServlet?method=9&id=${c.id }'/>"><img src="${c.imgurl }"/> </a></td><td>${c.description }</td><td><a href="<c:url value='/AdminServlet?method=4&id=${c.id }'/>">编辑</a><a href="<c:url value='/OrderServlet?method=4&id=${c.id }'/>">删除</a></td></tr></c:forEach></table><br>第${pb.pageCode }页/共${pb.totalPage }页<a href="<c:url value='/AdminServlet?method=2'/>">首页</a><c:if test="${pb.pageCode > 1}"><ahref="<c:url value='/AdminServlet?method=2&pageCode=${pb.pageCode-1}'/>">上一页</a></c:if><%--页码列表 --%><c:set var="begin" value="1" /><c:set var="end" value="10" /><!-- 定位begin和end --><c:choose><c:when test="${pb.totalPage <= 10}"><c:set var="begin" value="1" /><c:set var="end" value="${pb.totalPage}" /></c:when><c:otherwise><c:choose><c:when test="${pb.pageCode-4 <= 1 }"><c:set var="begin" value="1" /><c:set var="end" value="10" /></c:when><c:when test="${pb.pageCode+5 > pb.totalPage}"><c:set var="begin" value="${pb.totalPage-9}" /><c:set var="end" value="${pb.totalPage}" /></c:when><c:otherwise><c:set var="begin" value="${pb.pageCode-4}" /><c:set var="end" value="${pb.pageCode+5}" /></c:otherwise></c:choose></c:otherwise></c:choose><c:forEach begin="${begin}" end="${end}" var="i"><c:choose><c:when test="${pb.pageCode == i}">${i}</c:when><c:otherwise><a href="<c:url value='/AdminServlet?method=2&pageCode=${i}'/>">${i}</a></c:otherwise></c:choose></c:forEach><c:if test="${pb.pageCode < pb.totalPage}"><ahref="<c:url value='/AdminServlet?method=2&pageCode=${pb.pageCode+1}'/>">下一页</a></c:if><ahref="<c:url value='/AdminServlet?method=2&pageCode=${pb.totalPage }'/>">尾页</a></body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>add.jsp</title><style type="text/css"> body {text-align: center;font-size: 38px; }* {font-family: 华文楷体;font-size: 18px;color: #F0F "; }h1 {text-align: center;font-size: 38px; } </style></head><body><h1 style="font-size: 38px;">添加商品</h1><form action="<c:url value='/AdminServlet'/>" method="post"><input type="hidden" name="method" value="3"><table border="1" width="50%" align="center"><tr><td>商品名</td><td><input type="text" name="name" id="name" onfocus="nameFocus()"onblur="nameBlur()" /><div id="nameId"></div></td></tr><tr><td>价格</td><td><input type="text" name="price" id="tel" onfocus="telFocus()"onblur="telBlur()" /><div id="telId"></div></td></tr><tr><td>类型</td><td><input type="text" name="category" id="address" /></td></tr><tr><td>数量</td><td><input type="text" name="pnum" /></td></tr><tr><td>描述</td><td><input type="text" name="description" /></td></tr></table><input style="margin-right: 200px;" type="submit" value="添加" /></form></body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>edit.jsp</title></head><body style="text-align: center;"><h3>修改商品信息</h3><form action="<c:url value='/AdminServlet'/>" method="post"><input type="hidden" name="method" value="5"><input type="hidden" name="id" value="${product.id }"><table border="1" width="50%" align="center"><tr><td>商品名</td><td><input type="text" name="name" value="${product.name }" /></td></tr><tr><td>价格</td><td><input type="text" name="price" value="${product.price }" /></td></tr><tr><td>类型</td><td><input type="text" id="birthday" name="category"value="${product.category }" /></td></tr><tr><td>数量</td><td><input type="text" name="pnum" value="${product.pnum }" /></td></tr><tr><td>描述</td><td><input type="text" name="description"value="${product.description }" /></td></tr>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>list.jsp</title></head><body><center><h1>查看所有订单</h1><table border="2" width="80%"><tr align="left"><th>序号</th><th>订单号</th><th>订单金额</th><th>时间</th><th>状态</th><th>买家详情</th><th>物流信息</th><th>交易状态</th><th>操作</th></tr><c:forEach items="${allorderList}" var="order" varStatus="status"><tr><td>${status.count}</td><td>${order.id }</td><td>${order.totalMoney }</td><td>${order.ordertime}</td><td><c:if test="${order.paysate == 0 }">未支付</c:if><c:if test="${order.paysate == 1 }">已支付</c:if></td><td>${order.receiverName }</td><td><c:if test="${order.paysate == 0 }">未发货</c:if><c:if test="${order.paysate == 1 }">已发货</c:if></td><td>交易中</td><td><a href="<c:url value='/OrderServlet?method=4&id=${order.id }'/>">删除</a></td></tr><c:set value="${total + entry.key.price*entry.value}" var="total" /></c:forEach></table></center></body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>updateorder.jsp</title></head><body style="text-align: center;"><h3>修改订单信息</h3><form action="<c:url value='/AdminServlet'/>" method="post"><input type="hidden" name="method" value="5"><input type="hidden" name="id" value="${product.id }"><table border="1" width="50%" align="center"><tr><td>订单号</td><td>${order.id }</td></tr><tr><td>买家姓名</td><td><input type="text" name="receiverName"value="${order.receiverName }" /></td></tr><tr><td>收货地址</td><td><input type="text" id="birthday" name="receiverAddress"value="${order.receiverAddress }" /></td></tr><tr><td>收获电话</td><td><input type="text" name="receiverPhone"value="${order.receiverPhone }" /></td></tr><tr><td>物流信息</td><td>在路上</td></tr><tr><td>交易状态</td><td>交易中</td></tr><tr><td colspan="2" align="center"><input type="submit" value="更改" /></td></tr></table></form></body> </html>
<%@ page language="java" import="java.util.*" 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>upload.jsp</title></head><body><form method="post" action="/shopping/AdminServlet?method=8&id=${product.id }"enctype="multipart/form-data">选择一个文件:<input type="file" name="imgurl"/><br /><br /><input type="submit" value="上传" /></form></body> </html>
<tr><td colspan="2" align="center"><input type="submit" value="更改" /></td></tr></table></form></body> </html>
package cn.edu.aynu.rjxy.servlet;import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;import cn.edu.aynu.rjxy.bean.Admin; import cn.edu.aynu.rjxy.bean.Order; import cn.edu.aynu.rjxy.bean.Page; import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.service.AdminService; import cn.edu.aynu.rjxy.service.OrderService; import cn.edu.aynu.rjxy.service.ProductService; import cn.edu.aynu.rjxy.utils.CommonsUtils;public class AdminServlet extends HttpServlet {private AdminService aService = new AdminService();private ProductService ps = new ProductService();private OrderService os = new OrderService();private static final long serialVersionUID = 1L;// 上传文件存储目录private static final String UPLOAD_DIRECTORY = "img";// 上传配置private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MBprivate static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MBprivate static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MBpublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 处理中文乱码request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");// 获取隐藏字段method的值,并把它转换为int型int method = Integer.parseInt(request.getParameter("method"));switch (method) {case 1:this.login(request, response);break;case 2:this.query(request, response);break;case 3:this.add(request, response);break;case 4:this.loadForUpdate(request, response);break;case 5:this.edit(request, response);break;case 6:this.delete(request, response);break;case 7:this.order(request, response);break;case 8:this.uploadpicture(request, response);break;case 9:this.uploadForpicture(request, response);break;}}// 管理员登录public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 从请求中解析用户名和密码String username = request.getParameter("username");String password = request.getParameter("password");// 执行加载业务Admin a = aService.login(username, password);if (a != null) {HttpSession session = request.getSession();session.setAttribute("userId", a.getId());response.getWriter().print("登录成功" + a.getId());// 通过请求转发将pb带到list.jsp上去request.getRequestDispatcher("/admin/list.jsp").forward(request,response);} else {response.getWriter().print("登录失败,即将跳转到登录页面,请重新登录......");response.setHeader("Refresh", "3;url=/shopping/admin/login.jsp");}}// 管理员查看商品public void query(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 当前页有一个默认值为1int pageCode = 1;String s = request.getParameter("pageCode");// 如果请求中存在pageCode参数if (s != null && !s.trim().isEmpty()) {pageCode = Integer.parseInt(s);}// 查询当前页的记录Page pb = ps.queryByPage(pageCode);// 将pb保存在request域中request.setAttribute("pb", pb);// 通过请求转发将pb带到list.jsp上去request.getRequestDispatcher("/admin/list.jsp").forward(request,response);}// 管理员添加商品public void add(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 使用CommonUtils工具类将请求数据封装到bean中Product p = CommonsUtils.toBean(request.getParameterMap(),Product.class);// 使用UUID作为id属性的值 p.setId(CommonsUtils.uuid());// p.setImgurl(uploadPath);// 执行添加 ps.add(p);// 输出添加成功提示response.getWriter().print("添加成功");}// 加载商品为修改做准备public void loadForUpdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 从请求中获取客户的idString id = request.getParameter("id");// 执行加载业务Product p = ps.findById(id);// 将Customer对象c保存在request域中request.setAttribute("product", p);// t=通过请求转发将customer对象显示在list.jsp页面上request.getRequestDispatcher("/admin/edit.jsp").forward(request,response);}// 管理员修改商品信息public void edit(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 使用CommonUtils工具类将请求数据封装到bean中Product p = CommonsUtils.toBean(request.getParameterMap(),Product.class);// 执行更改业务 ps.edit(p);// 给客户端发送更改成功提示response.getWriter().print("更改成功");}// 管理员删除商品public void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 从请求中获取idString id = request.getParameter("id");// 执行删除 ps.delete(id);// 给客户端发送删除成功提示response.getWriter().print("删除成功");}// 管理员查看所有订单public void order(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Order> list = os.findAllOrder();request.setAttribute("allorderList", list);request.getRequestDispatcher("/admin/orderproduct.jsp").forward(request, response);}// 为上传照片做准备public void uploadForpicture(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String id = request.getParameter("id");Product p = ps.findById(id);System.out.println(id + "id");ps.upload(p, id);// 将Customer对象c保存在request域中request.setAttribute("product", p);// t=通过请求转发将customer对象显示在list.jsp页面上request.getRequestDispatcher("/admin/upload.jsp").forward(request,response);}// 管理员上传照片public void uploadpicture(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 检测是否为多媒体上传if (!ServletFileUpload.isMultipartContent(request)) {// 如果不是则停止PrintWriter writer = response.getWriter();writer.println("Error: 表单必须包含 enctype=multipart/form-data");writer.flush();return;}// 配置上传参数DiskFileItemFactory factory = new DiskFileItemFactory();// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD);// 设置临时存储目录factory.setRepository(new File(System.getProperty("java.io.tmpdir")));ServletFileUpload upload = new ServletFileUpload(factory);// 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE);// 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE);// 构造临时路径来存储上传的文件// 这个路径相对当前应用的目录String uploadPath = getServletContext().getRealPath("")+ File.separator + UPLOAD_DIRECTORY;// 如果目录不存在则创建File uploadDir = new File(uploadPath);if (!uploadDir.exists()) {uploadDir.mkdir();}try {// 解析请求的内容提取文件数据@SuppressWarnings("unchecked")List<FileItem> formItems = upload.parseRequest(request);if (formItems != null && formItems.size() > 0) {// 迭代表单数据for (FileItem item : formItems) {// 处理不在表单中的字段if (!item.isFormField()) {Date date = new Date();DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");String time = format.format(date);String filePath = uploadPath + File.separator + time+ ".jpg";File storeFile = new File(filePath);// 使用CommonUtils工具类将请求数据封装到bean中Product p = CommonsUtils.toBean(request.getParameterMap(), Product.class);String url = "/" + "shopping" + "/" + UPLOAD_DIRECTORY+ "/" + time + ".jpg";p.setImgurl(url);// 执行更改业务 ps.upload(p, p.getId());// 在控制台输出文件的上传路径 System.out.println(filePath);System.out.println("/" + "shopping" + "/"+ UPLOAD_DIRECTORY + "/" + time + ".jpg");// 保存文件到硬盘 item.write(storeFile);request.setAttribute("message", "文件上传成功!");}}}} catch (Exception ex) {request.setAttribute("message", "错误信息: " + ex.getMessage());}response.getWriter().print("上传成功,三秒后跳转到功能界面......");response.setHeader("Refresh", "3;url=/shopping/admin/list.jsp");}}
package cn.edu.aynu.rjxy.servlet;import java.io.IOException; import java.util.ArrayList; 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 cn.edu.aynu.rjxy.bean.Order; import cn.edu.aynu.rjxy.bean.OrderItem; import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.bean.User; import cn.edu.aynu.rjxy.service.OrderService; import cn.edu.aynu.rjxy.utils.CommonsUtils;public class OrderServlet extends HttpServlet {private OrderService orderService = new OrderService();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 处理中文乱码request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");// 获取隐藏字段method的值,并把它转换为int型int method = Integer.parseInt(request.getParameter("method"));switch (method) {case 1:this.addOrder(request, response);break;case 2:this.findMyOrder(request, response);break;case 3:this.findOrderItem(request, response);break;case 4:this.delete(request, response);break;}}// 添加订单和订单项public void addOrder(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {/*** 1、判断用户是否登录,如果未登录就重定向到login.jsp 2、使用工具类将订单表中的信息封装成order对象,补全剩余的字段* 3、从session中获取购物车,遍历购物车,创建订单项,把它们加入list集合 4、添加订单和订单项*/User user = (User) request.getSession().getAttribute("user");if (user == null) {response.sendRedirect("jsp/login.jsp");return;}Order order = CommonsUtils.toBean(request.getParameterMap(),Order.class);// 补全字段 order.setId(CommonsUtils.uuid());order.setOrdertime(new Date());order.setPaysate(0);order.setUser_id(user.getId());Map<Product, Integer> cart = (Map<Product, Integer>) request.getSession().getAttribute("cart");List<OrderItem> list = new ArrayList<OrderItem>();for (Product p : cart.keySet()) {OrderItem orderItem = new OrderItem();orderItem.setId(CommonsUtils.uuid());orderItem.setOrder_id(order.getId());orderItem.setProduct_id(p.getId());orderItem.setBuynum(cart.get(p));orderItem.setSubtotal(p.getPrice() * orderItem.getBuynum());// 订单项加入list集合 list.add(orderItem);}order.setList(list);// 添加订单和订单项String result = orderService.addOrder(order);request.setAttribute("orderResult", result);response.getWriter().print("购买成功,三秒后跳转到商品界面......");response.setHeader("Refresh", "3;url=/shopping/index.jsp");}// 查看我的订单public void findMyOrder(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {/*** 1、用户已经登录,从session中获取用户信息,从用户信息中得到user_id 2、调用方法得到用户的订单的集合* 3、通过请求转发将订单集合显示在myorder.jsp页面上*/User user = (User) request.getSession().getAttribute("user");String user_id = user.getId();List<Order> list = orderService.findMyOrder(user_id);request.setAttribute("myorderList", list);request.getRequestDispatcher("/jsp/myorder.jsp").forward(request,response);}// 查看我的订单的详情public void findOrderItem(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {/*** 1、从请求转发中获取订单的id 2、调用方法得到订单详情的集合 3、通过请求转发将订单详情在orderItem.jsp页面上显示*/String order_id = request.getParameter("order_id");System.out.println(order_id + "ssssss");List<OrderItem> list = orderService.findOrderItem(order_id);request.setAttribute("orderItemList", list);request.getRequestDispatcher("/jsp/orderitem.jsp").forward(request,response);}public void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 从请求中获取idString id = request.getParameter("id");// 执行删除客户业务 orderService.delete(id);// 给客户端发送删除成功提示response.getWriter().print("删除成功,三秒后跳转到功能界面......");response.setHeader("Refresh", "3;url=/shopping/admin/list.jsp");} }
package cn.edu.aynu.rjxy.servlet;import java.io.IOException; import java.util.HashMap; import java.util.Iterator; 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 javax.servlet.http.HttpSession;import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.service.ProductService;/*** 调用ProductService的方法* * @author Administrator* */ public class ProductServlet extends HttpServlet {private ProductService ps = new ProductService();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 处理中文乱码request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");// 获取隐藏字段method的值,并把它转换为int型int method = Integer.parseInt(request.getParameter("method"));switch (method) {case 1:this.findAll(request, response);break;case 2:this.addCart(request, response);break;}}// 处理查询所有商品的请求public void findAll(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Product> list = ps.findAll();request.setAttribute("listProduct", list);// 通过请求转发将商品信息显示在product.jsp页面上request.getRequestDispatcher("/jsp/product.jsp").forward(request,response);}// 处理添加购物车的请求public void addCart(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取商品的idString id = request.getParameter("id");// 得到商品Product p = ps.findById(id);// 购物车是保存在session中HttpSession session = request.getSession();// 从session中拿到购物车Map<Product, Integer> cart = (Map<Product, Integer>) session.getAttribute("cart");// 如果cart不存在,就创建购物车if (cart == null) {cart = new HashMap<Product, Integer>();}/*** 遍历Map中的所有key也就是商品对象,如果发现有的商品的id和 即将加入购物车的id相同,就在原来的数量上+1*/Iterator<Product> it = cart.keySet().iterator();boolean f = true;while (it.hasNext()) {Product pp = (Product) it.next();if (pp.getId().equals(p.getId())) {cart.put(pp, cart.get(pp) + 1);f = false;}}// 如果没有发现购物车原来相同的商品,就直接加入if (f) {cart.put(p, 1);}// 将cart放入sessionsession.setAttribute("cart", cart);// 重定向response.sendRedirect("jsp/cart.jsp");}}
package cn.edu.aynu.rjxy.servlet;import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import cn.edu.aynu.rjxy.bean.User; import cn.edu.aynu.rjxy.exception.UserException; import cn.edu.aynu.rjxy.service.UserService; import cn.edu.aynu.rjxy.utils.CommonsUtils;/*** 调用UserService里面的方法* * @author Administrator* */ public class UserServlet extends HttpServlet {private UserService userService = new UserService();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 处理中文乱码request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");// 获取隐藏字段method的值,并把它转换为int型int method = Integer.parseInt(request.getParameter("method"));switch (method) {case 1:this.register(request, response);break;case 2:this.login(request, response);break;}}public void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {/*** 1、将注册表单中的用户信息封装到user对象中 2、将获取的UUID值作为user对象的id* 3、注册,如果发生异常,就到register.jsp页面上显示:用户已存在 如果成功,显示注册成功,3秒后就跳转到index.jsp页面。*/User user = CommonsUtils.toBean(request.getParameterMap(), User.class);user.setId(CommonsUtils.uuid());try {userService.register(user);request.setAttribute("msg", "注册成功");request.getRequestDispatcher("/jsp/index.jsp").forward(request,response);} catch (UserException e) {request.setAttribute("msg", e.getMessage());// 将用户在注册表单中输入的信息保存在request域中,请求转发的register.jsp,目的回显request.setAttribute("user", user);request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);}}public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/*** 1、将用户登录表单中的信息封装成User对象 2、登录,如果发生异常,就转发到login.jsp页面,显示:异常信息* 如果成功,就将查询到的user对象u,存放到session域中 然后转发到shopping.jsp页面,显示:欢迎用户登录*/User user = CommonsUtils.toBean(request.getParameterMap(), User.class);System.out.println(user + "-------->");try {User u = userService.login(user);System.out.println(u + ">>>>");// 将u存放到session域中request.getSession().setAttribute("user", u);request.getRequestDispatcher("/jsp/index.jsp").forward(request,response);} catch (UserException e) {request.setAttribute("msg", e.getMessage());request.setAttribute("user", user); // 回显request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);}} }
package cn.edu.aynu.rjxy.service;import java.sql.SQLException;import cn.edu.aynu.rjxy.bean.Admin; import cn.edu.aynu.rjxy.dao.AdminDao;public class AdminService {private AdminDao aDao = new AdminDao();/*** 根据用户名和密码查询用户* * @param cid*/public Admin login(String username, String password) {try {return aDao.findByCid(username, password);} catch (SQLException e) {throw new RuntimeException(e);}} }
package cn.edu.aynu.rjxy.service;import java.sql.SQLException; import java.util.List;import cn.edu.aynu.rjxy.bean.Order; import cn.edu.aynu.rjxy.bean.OrderItem; import cn.edu.aynu.rjxy.dao.OrderDao; import cn.edu.aynu.rjxy.dao.OrderItemDao; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 调用dao里面的方法* * @author Administrator* */ public class OrderService {private OrderDao orderDao = new OrderDao();private OrderItemDao orderItemDao = new OrderItemDao();// 添加订单和订单项public String addOrder(Order order) {try {// 开启事物 JDBCUtils.startTransaction();// 添加订单 orderDao.add(order);// 获取订单项的集合List<OrderItem> list = order.getList();// 遍历订单项目,依次将它们插入orderitem表中for (OrderItem orderItem : list) {// 添加订单项 orderItemDao.addItem(orderItem);}// 提交事务 JDBCUtils.commit();return "success";} catch (Exception e) {// 回滚事务 JDBCUtils.rollback();e.printStackTrace();return "fail";}}// 查看所有的订单public List<Order> findAllOrder() {try {return orderDao.findAllOrder();} catch (SQLException e) {throw new RuntimeException(e);}}// 查看我的订单public List<Order> findMyOrder(String user_id) {try {return orderDao.findOrderByUser_id(user_id);} catch (SQLException e) {throw new RuntimeException(e);}}// 查看某个订单public List<OrderItem> findOrderItem(String order_id) {try {return orderItemDao.findOrderItem(order_id);} catch (SQLException e) {throw new RuntimeException(e);}}// 删除某个订单public void delete(String id) {try {orderDao.deleteById(id);} catch (SQLException e) {throw new RuntimeException(e);}} }
package cn.edu.aynu.rjxy.service;import java.sql.SQLException; import java.util.List;import cn.edu.aynu.rjxy.bean.Page; import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.dao.ProductDao;/*** 调用ProductDao的方法* * @author Administrator* */ public class ProductService {private ProductDao pDao = new ProductDao();/*** 添加商品* * @param c*/public void add(Product p) {try {pDao.insert(p);} catch (SQLException e) {throw new RuntimeException(e);}}//上传照片public void upload(Product p,String id){try {pDao.insertURL(p, id);} catch (SQLException e) {throw new RuntimeException(e);}}/*** 删除客户业务*/public void delete(String cid) {try {pDao.delete(cid);} catch (SQLException e) {throw new RuntimeException(e);}}/*** 编辑修改商品* * @param c*/public void edit(Product p) {try {pDao.update(p);} catch (SQLException e) {throw new RuntimeException(e);}}// 查询所有商品public List<Product> findAll() {try {return pDao.findAll();} catch (SQLException e) {throw new RuntimeException(e);}}// 查看某一商品public Product findById(String id) {try {return pDao.findProductById(id);} catch (SQLException e) {throw new RuntimeException(e);}}/*** 分页查询* * @param pageCode* @return*/public Page queryByPage(int pageCode) {try {// 获取总记录数int totalRecord = pDao.queryTotalRecord();// 创建PagePage pb = new Page(pageCode, totalRecord);// 查询当前页的记录List<Product> datas = pDao.queryByPage((pageCode - 1)* pb.getPageSize(), pb.getPageSize());// 将datas封装到pb pb.setDatas(datas);return pb;} catch (SQLException e) {throw new RuntimeException(e);}} }
package cn.edu.aynu.rjxy.service;import java.sql.SQLException;import cn.edu.aynu.rjxy.bean.User; import cn.edu.aynu.rjxy.dao.UserDao; import cn.edu.aynu.rjxy.exception.UserException;/*** 调用dao层的方法* * @author Administrator* */ public class UserService {private UserDao userDao = new UserDao();/*** 用户注册 1、检测输入的用户名是否存在,如果存在抛出异常“用户已存在” 2、把输入的用户添加到数据库中的user表* * @throws UserException*/public void register(User user) throws UserException {try {// 检测用户是否存在User u = userDao.findByUsername(user.getUsername());// 如果存在抛出异常否则添加用户到user表if (u != null) {throw new UserException("用户已经存在");} else {userDao.add(user);}} catch (SQLException e) {throw new RuntimeException(e);}}/*** 用户登录* * @throws UserException*/public User login(User user) throws UserException {try {// 根据用户名查询user表得到user对象uUser u = userDao.findByUsername(user.getUsername());/*** 如果u为null,说明用户不存在,抛出异常,显示用户不存在 否则说明用户存在,检测u对象中的密码和用户输入的面貌是否一致* 如果一致,返回查询到的u否则抛出异常,显示密码错误*/if (u == null) {throw new UserException("用户名不存在");}// 查询到的用户密码和用户名输入的密码不一致if (!u.getPassword().equals(user.getPassword())) {throw new UserException("密码错误");}return u;} catch (SQLException e) {throw new RuntimeException(e);}} }
package cn.edu.aynu.rjxy.dao;import java.sql.SQLException;import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler;import cn.edu.aynu.rjxy.bean.Admin; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 对管理员表的操作* * @author Administrator* */ public class AdminDao {QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());/*** 根据用户名和用户密码查询* * @return* @throws SQLException*/public Admin findByCid(String username, String password)throws SQLException {String sql = "select * from admin where username=?&&password=?";Admin admin = qr.query(sql, new BeanHandler<Admin>(Admin.class),username, password);return admin;} }
package cn.edu.aynu.rjxy.dao;import java.sql.Connection; import java.sql.Date; import java.sql.SQLException; import java.util.List;import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler;import cn.edu.aynu.rjxy.bean.Order; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 对order1表的操作* * @author Administrator* */ public class OrderDao {private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());// 添加订单到数据库表order1中public void add(Order order) throws Exception {Connection conn = JDBCUtils.getConnection();String sql = "insert into order1 values(?,?,?,?,?,?,?,?)";// 订单生成时间,由java.util.Date----->java.sql.DateDate date = new Date(order.getOrdertime().getTime());qr.update(conn, sql, order.getId(), order.getTotalMoney(), order.getReceiverAddress(), order.getReceiverName(), order.getReceiverPhone(), order.getPaysate(), date, order.getUser_id());}// 查看所有用户的订单public List<Order> findAllOrder() throws SQLException {String sql = "select * from order1";return qr.query(sql, new BeanListHandler<Order>(Order.class));}// 根据user_id查看用户的订单public List<Order> findOrderByUser_id(String user_id) throws SQLException {String sql = "select * from order1 where user_id = ?";return qr.query(sql, new BeanListHandler<Order>(Order.class), user_id);}// 根据user_id删除用户的订单public void deleteById(String id) throws SQLException {String sql = "delete from order1 where id=?";qr.update(sql, id);} }
package cn.edu.aynu.rjxy.dao;import java.sql.Connection; import java.sql.SQLException; import java.util.List;import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler;import cn.edu.aynu.rjxy.bean.OrderItem; import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 对orderItem表的操作* * @author Administrator* */ public class OrderItemDao {private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());// 添加订单项到数据库表orderitem中public void addItem(OrderItem orderItem) throws Exception {Connection conn = JDBCUtils.getConnection();String sql = "insert into orderitem values(?,?,?,?,?)";qr.update(conn, sql, orderItem.getId(), orderItem.getOrder_id(),orderItem.getProduct_id(), orderItem.getBuynum(), orderItem.getSubtotal());}// 查询某一个订单的所有订单项public List<OrderItem> findOrderItem(String order_id) throws SQLException {// 查询某一订单所包含的订单项String sql = "select * from orderitem where order_id = ?";List<OrderItem> orderItemList = qr.query(sql,new BeanListHandler<OrderItem>(OrderItem.class), order_id);// 查询某一订单所包含的订单项对应的商品信息sql = "select p.id,p.name,p.price from product p,orderitem oi where p.id = oi.product_id and order_id = ?";List<Product> productList = qr.query(sql, new BeanListHandler<Product>(Product.class), order_id);// 将查询出来的商品作为订单项的属性进行添加for (OrderItem oi : orderItemList) {for (Product p : productList) {if (oi.getProduct_id().equals(p.getId())) {oi.setProduct(p);}}}return orderItemList;} }
package cn.edu.aynu.rjxy.dao;import java.sql.SQLException; 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 org.apache.commons.dbutils.handlers.ScalarHandler;import cn.edu.aynu.rjxy.bean.Product; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 对product表进行增删改查* * @author Administrator* */ public class ProductDao {QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());/*** 添加商品* * @param c* @throws SQLException*/public void insert(Product p) throws SQLException {String sql = "insert into product(id,name,price,category,pnum,description) values(?,?,?,?,?,?)";qr.update(sql, p.getId(), p.getName(), p.getPrice(), p.getCategory(), p.getPnum(), p.getDescription());}public void insertURL(Product p,String id) throws SQLException {String sql = "update product set imgurl = ? where id =?";qr.update(sql, p.getImgurl(),id);}// 查询所有商品public List<Product> findAll() throws SQLException {String sql = "select * from product";List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));return list;}// 根据id查找商品public Product findProductById(String id) throws SQLException {String sql = "select * from product where id=?";return qr.query(sql, new BeanHandler<Product>(Product.class), id);}/*** 根据传过来的id,删除商品* * @throws SQLException* */public void delete(String id) throws SQLException {String sql = "delete from product where id=?";qr.update(sql, id);}/*** 修改商品属性* * @throws SQLException*/public void update(Product p) throws SQLException {String sql = "update product set name=?,price=?,category=?,pnum=?,imgurl=?,description=? where id=?";qr.update(sql, p.getName(), p.getPrice(), p.getCategory(), p.getPnum(),p.getImgurl(), p.getDescription(), p.getId());}/*** 查询总记录数* * @throws SQLException* */public int queryTotalRecord() throws SQLException {String sql = "select count(*) from product";Long num = qr.query(sql, new ScalarHandler<Long>());return num.intValue();}/*** 分页查询* * @throws SQLException* */public List<Product> queryByPage(int recordStartIndex, int pageSize)throws SQLException {String sql = "select * from product limit ?,?";List<Product> datas = qr.query(sql, new BeanListHandler<Product>(Product.class), recordStartIndex, pageSize);return datas;} }
package cn.edu.aynu.rjxy.dao;import java.sql.SQLException;import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler;import cn.edu.aynu.rjxy.bean.User; import cn.edu.aynu.rjxy.utils.JDBCUtils;/*** 对User表的操作* * @author Administrator* */ public class UserDao {QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());/*** 添加用户到user表* * @throws SQLException*/public void add(User user) throws SQLException {String sql = "insert into user(id,username,password) values(?,?,?)";qr.update(sql, user.getId(), user.getUsername(), user.getPassword());}/*** 通过用户名查找用户* * @throws SQLException*/public User findByUsername(String username) throws SQLException {String sql = "select * from user where username = ?";User user = qr.query(sql, new BeanHandler<User>(User.class), username);return user;} }
http://lijun0349-163-com.iteye.com/blog/2008680
http://blog.sina.com.cn/s/blog_ae96abfd0101p9bf.html