做業終於作完了,好開心。。。。。。雖然這一週經歷不是那麼順利,可是以爲仍是收穫了很多,有過想哭的衝動,代碼不會寫,事情辦很差,各類發愁。空間裏發小發了帶父母出去遊玩的照片,瞬間能量值不知道是被擊退的多仍是回返的多。不過今天終於補滿能量值。下面我來分享一下個人運行結果。css
下面我把我管理後臺的代碼粘貼一下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>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}"> <a href="<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}"> <a href="<c:url value='/AdminServlet?method=2&pageCode=${pb.pageCode+1}'/>">下一頁</a> </c:if> <a href="<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; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB 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.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 { // 當前頁有一個默認值爲1 int 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 { // 從請求中獲取客戶的id String 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 { // 從請求中獲取id String 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 { /** * 一、判斷用戶是否登陸,若是未登陸就重定向到login.jsp 二、使用工具類將訂單表中的信息封裝成order對象,補全剩餘的字段 * 三、從session中獲取購物車,遍歷購物車,建立訂單項,把它們加入list集合 四、添加訂單和訂單項 */ 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 { /** * 一、用戶已經登陸,從session中獲取用戶信息,從用戶信息中獲得user_id 二、調用方法獲得用戶的訂單的集合 * 三、經過請求轉發將訂單集合顯示在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 { /** * 一、從請求轉發中獲取訂單的id 二、調用方法獲得訂單詳情的集合 三、經過請求轉發將訂單詳情在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 { // 從請求中獲取id String 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 { // 獲取商品的id String 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放入session session.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 { /** * 一、將註冊表單中的用戶信息封裝到user對象中 二、將獲取的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 { /** * 一、將用戶登陸表單中的信息封裝成User對象 二、登陸,若是發生異常,就轉發到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(); // 建立Page Page 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(); /** * 用戶註冊 一、檢測輸入的用戶名是否存在,若是存在拋出異常「用戶已存在」 二、把輸入的用戶添加到數據庫中的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對象u User 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.Date Date 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/2008680java
http://blog.sina.com.cn/s/blog_ae96abfd0101p9bf.htmlsql