购物车设计
实体类
1 import java.io.Serializable; 2 import java.util.HashMap; 3 import java.util.Map; 4 5 import com.itheima.domain.Book; 6 /* 7 * 购物车: 8 * 同一本书对应着一个购物项 9 */ 10 public class Cart implements Serializable { 11 //key:购物项对应的书籍的ID,value:书籍对应的购物项 12 private Map<String, CartItem> items = new HashMap<String, CartItem>(); 13 private int totalNum;//总数量 14 private float totalMoney;//总金额:付款金额 15 public Map<String, CartItem> getItems() { 16 return items; 17 } 18 public int getTotalNum() { 19 totalNum = 0; 20 for(Map.Entry<String, CartItem> me:items.entrySet()){ 21 totalNum+=me.getValue().getNum(); 22 } 23 return totalNum; 24 } 25 public float getTotalMoney() { 26 totalMoney = 0; 27 for(Map.Entry<String, CartItem> me:items.entrySet()){ 28 totalMoney+=me.getValue().getPrice(); 29 } 30 return totalMoney; 31 } 32 //项购物车的items中添加一本书 33 public void addBook(Book book){ 34 if(items.containsKey(book.getId())){ 35 //items有这本书对应的购物项了 36 CartItem item = items.get(book.getId()); 37 item.setNum(item.getNum()+1); 38 }else{ 39 CartItem item = new CartItem(book); 40 item.setNum(1); 41 items.put(book.getId(), item); 42 } 43 } 44 }
1 import java.io.Serializable; 2 3 import com.itheima.domain.Book; 4 /** 5 * 代表着一个购物项,一项就对应着一本书 6 * @author wzhting 7 * 8 */ 9 public class CartItem implements Serializable { 10 private Book book; 11 private int num;//数量 12 private float price;//小计 13 14 public CartItem(Book book){ 15 this.book = book; 16 } 17 18 public Book getBook() { 19 return book; 20 } 21 22 public void setBook(Book book) { 23 this.book = book; 24 } 25 26 public int getNum() { 27 return num; 28 } 29 30 public void setNum(int num) { 31 this.num = num; 32 } 33 34 public float getPrice() { 35 return book.getMoney()*num; 36 } 37 38 // public void setPrice(float price) { 39 // this.price = price; 40 // } 41 42 }
控制层
1 public class ControllerServlet extends HttpServlet { 2 private BusinessService s = new BusinessServiceImpl(); 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 String op = request.getParameter("op"); 6 if("buyBook".equals(op)){ 7 buyBook(request,response); 8 }else if("delOneFormCart".equals(op)){ 9 delOneFormCart(request,response); 10 }else if("changeCartItemNum".equals(op)){ 11 changeCartItemNum(request,response); 12 } 13 } 14 //修改购物项的数量 15 private void changeCartItemNum(HttpServletRequest request, 16 HttpServletResponse response)throws ServletException, IOException { 17 String bookId = request.getParameter("bookId"); 18 String newnum = request.getParameter("newnum"); 19 Cart cart = (Cart) request.getSession().getAttribute("cart"); 20 cart.getItems().get(bookId).setNum(Integer.parseInt(newnum)); 21 response.sendRedirect(request.getContextPath()+"/showCart.jsp"); 22 } 23 //从购物车中删除一项 24 private void delOneFormCart(HttpServletRequest request, 25 HttpServletResponse response) throws ServletException, IOException{ 26 String bookId = request.getParameter("bookId"); 27 Cart cart = (Cart) request.getSession().getAttribute("cart"); 28 cart.getItems().remove(bookId); 29 response.sendRedirect(request.getContextPath()+"/showCart.jsp"); 30 } 31 //把书籍放入购物车 32 private void buyBook(HttpServletRequest request, 33 HttpServletResponse response)throws ServletException, IOException { 34 //获取要购物买的书籍 35 String bookId = request.getParameter("bookId"); 36 Book book = s.findBookById(bookId); 37 //从HttpSession中先查,不在时创建一个新的购物车 38 HttpSession session = request.getSession(); 39 Cart cart = (Cart)session.getAttribute("cart"); 40 if(cart==null){ 41 cart = new Cart(); 42 session.setAttribute("cart", cart); 43 } 44 //把书籍放入购物车中 45 cart.addBook(book); 46 //提示购买成功 47 response.getWriter().write("<script type='text/javascript'>alert('购买成功')</script>"); 48 response.setHeader("Refresh", "0;URL="+request.getContextPath()); 49 } 50 public void doPost(HttpServletRequest request, HttpServletResponse response) 51 throws ServletException, IOException { 52 doGet(request, response); 53 } 54 55 }
视图层
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ include file="/top.jsp"%> 3 <c:if test="${empty sessionScope.cart.items}"> 4 您还没有购买任何商品 5 </c:if> 6 <c:if test="${!empty sessionScope.cart.items }"> 7 <h3>您购买的商品如下</h3> 8 <table border="1" width="438"> 9 <tr> 10 <th>书名</th> 11 <th>数量</th> 12 <th>单价</th> 13 <th>小计</th> 14 <th>操作</th> 15 </tr> 16 <c:forEach items="${sessionScope.cart.items}" var="me" varStatus="vs"> 17 <tr class="${vs.index%2==0?'odd':'even'}"> 18 <td>${me.value.book.name}</td> 19 <td><input type="text" size="3" value="${me.value.num}" onchange="changeNum(this,${me.value.num},'${me.key}')"/></td> 20 <td>${me.value.book.money}</td> 21 <td>${me.value.price}</td> 22 <td> 23 <a href="javascript:delOneItem('${me.key}')">删除</a> 24 </td> 25 </tr> 26 </c:forEach> 27 <tr> 28 <td colspan="5" align="right"> 29 总数量:${sessionScope.cart.totalNum} 30 应付金额:${sessionScope.cart.totalMoney} 31 <a href="${pageContext.request.contextPath}/servlet/ControllerServlet?op=genOrders">去付款</a> 32 </td> 33 </tr> 34 </table> 35 </c:if> 36 <script type="text/javascript"> 37 //输入验证:客户端验证(js);服务器段验证(保证安全);开发中:客户端+服务器段 38 39 function delOneItem(bookId){ 40 var sure = window.confirm("确定要删除该项吗?"); 41 if(sure){ 42 window.location.href="${pageContext.request.contextPath}/servlet/ControllerServlet?op=delOneFormCart&bookId="+bookId; 43 } 44 } 45 function changeNum(inputObj,oldNum,bookId){ 46 var newnum = inputObj.value; 47 48 if(!/^[1-9][0-9]*$/.test(newnum)){ 49 alert("请输入正确的数值"); 50 inputObj.value = oldNum; 51 return; 52 } 53 54 var sure = window.confirm("确定要修改数量吗"); 55 if(sure){ 56 window.location.href="${pageContext.request.contextPath}/servlet/ControllerServlet?op=changeCartItemNum&bookId="+bookId+"&newnum="+newnum; 57 }else{ 58 inputObj.value = oldNum; 59 } 60 } 61 </script> 62 </body> 63 </html>
生成订单
表的设计
实体类设计
1 import java.io.Serializable; 2 import java.util.ArrayList; 3 import java.util.List; 4 //订单 5 public class Orders implements Serializable { 6 private String ordersnum;//订单号,作为主键 7 private float money;//订单金额----购物车的总金额 8 private int num;//有多少件商品 9 private int status;//订单状态 0未付款 1已付款 2 已发货 10 private Customer customer; 11 private List<OrdersItem> items = new ArrayList<OrdersItem>();//该订单对应的订单项 12 13 public String getOrdersnum() { 14 return ordersnum; 15 } 16 public void setOrdersnum(String ordersnum) { 17 this.ordersnum = ordersnum; 18 } 19 public float getMoney() { 20 return money; 21 } 22 public void setMoney(float money) { 23 this.money = money; 24 } 25 public int getNum() { 26 return num; 27 } 28 public void setNum(int num) { 29 this.num = num; 30 } 31 public int getStatus() { 32 return status; 33 } 34 public void setStatus(int status) { 35 this.status = status; 36 } 37 public Customer getCustomer() { 38 return customer; 39 } 40 public void setCustomer(Customer customer) { 41 this.customer = customer; 42 } 43 public List<OrdersItem> getItems() { 44 return items; 45 } 46 public void setItems(List<OrdersItem> items) { 47 this.items = items; 48 } 49 50 }
1 import java.io.Serializable; 2 3 public class OrdersItem implements Serializable { 4 private String id;//主键 5 private int num;//订单项数量 6 private float money;//小计 7 private Book book; 8 public String getId() { 9 return id; 10 } 11 public void setId(String id) { 12 this.id = id; 13 } 14 public int getNum() { 15 return num; 16 } 17 public void setNum(int num) { 18 this.num = num; 19 } 20 public float getMoney() { 21 return money; 22 } 23 public void setMoney(float money) { 24 this.money = money; 25 } 26 public Book getBook() { 27 return book; 28 } 29 public void setBook(Book book) { 30 this.book = book; 31 } 32 33 }
控制器设计
1 public class ControllerServlet extends HttpServlet { 2 private BusinessService s = new BusinessServiceImpl(); 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 String op = request.getParameter("op"); 6 if("showMyOrders".equals(op)){ 7 showMyOrders(request,response); 8 } 9 } 10 //查看用户自己的订单 11 private void showMyOrders(HttpServletRequest request, 12 HttpServletResponse response) throws ServletException, IOException{ 13 HttpSession session = request.getSession(); 14 Customer c = (Customer) session.getAttribute("customer"); 15 if(c==null){ 16 response.getWriter().write("<script type='text/javascript'>alert('请先登录')</script>"); 17 response.setHeader("Refresh", "0;URL="+request.getContextPath()+"/login.jsp"); 18 return; 19 } 20 List<Orders> os = s.findOrdersByCustomer(c.getId()); 21 request.setAttribute("os", os); 22 request.getRequestDispatcher("/showOrders.jsp").forward(request, response); 23 } 24 }
DAO层
1 import org.apache.commons.dbutils.QueryRunner; 2 import org.apache.commons.dbutils.handlers.BeanHandler; 3 import org.apache.commons.dbutils.handlers.BeanListHandler; 4 5 import com.itheima.dao.OrdersDao; 6 import com.itheima.domain.Orders; 7 import com.itheima.domain.OrdersItem; 8 import com.itheima.util.DBCPUtil; 9 10 public class OrdersDaoMySQLImpl implements OrdersDao { 11 private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource()); 12 13 public void save(Orders os) { 14 if(os==null) 15 throw new IllegalArgumentException("保存的订单不能为空"); 16 if(os.getCustomer()==null) 17 throw new IllegalArgumentException("请设置订单所属的客户"); 18 //保存订单的基本信息 19 try { 20 qr.update("insert into orders (ordersnum,money,num,status,customerid) values(?,?,?,?,?)", 21 os.getOrdersnum(),os.getMoney(),os.getNum(), 22 os.getStatus(),os.getCustomer().getId()); 23 //保存订单项信息 24 List<OrdersItem> items = os.getItems(); 25 if(items!=null&&items.size()>0){ 26 for(OrdersItem item:items){ 27 qr.update("insert into ordersitem (id,num,money,bookid,ordersnum) values(?,?,?,?,?)", 28 item.getId(),item.getNum(),item.getMoney(), 29 item.getBook().getId(),os.getOrdersnum()); 30 } 31 } 32 } catch (SQLException e) { 33 throw new RuntimeException(e); 34 } 35 } 36 37 public void update(Orders os) { 38 try { 39 qr.update("update orders set money=?,num=?,status=? where ordersnum=?", 40 os.getMoney(),os.getNum(), 41 os.getStatus(),os.getOrdersnum()); 42 } catch (SQLException e) { 43 throw new RuntimeException(e); 44 } 45 } 46 47 public Orders findByOrdersNum(String ordersNum) { 48 try { 49 return qr.query("select * from orders where ordersnum=?", new BeanHandler<Orders>(Orders.class), ordersNum); 50 } catch (SQLException e) { 51 throw new RuntimeException(e); 52 } 53 } 54 55 public List<Orders> findOrdersByCustomer(String customerId) { 56 try { 57 return qr.query("select * from orders where customerid=? order by ordersnum desc", new BeanListHandler<Orders>(Orders.class), customerId); 58 } catch (SQLException e) { 59 throw new RuntimeException(e); 60 } 61 } 62 63 }
视图层
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ include file="/top.jsp"%> 3 <c:if test="${empty os}"> 4 您还没有下过单 5 </c:if> 6 <c:if test="${!empty os }"> 7 <h3>一个月的订单如下</h3> 8 <table border="1" width="438"> 9 <tr> 10 <th>订单号</th> 11 <th>金额</th> 12 <th>状态</th> 13 <th>操作</th> 14 </tr> 15 <c:forEach items="${os}" var="o" varStatus="vs"> 16 <tr class="${vs.index%2==0?'odd':'even'}"> 17 <td>${o.ordersnum}</td> 18 <td>${o.money}</td> 19 <td> 20 <c:choose> 21 <c:when test="${o.status==0}"> 22 未付款<a href="${pageContext.request.contextPath}/servlet/ControllerServlet?op=payUI&ordersnum=${o.ordersnum}">付款</a> 23 </c:when> 24 <c:when test="${o.status==1}"> 25 已付款 26 </c:when> 27 <c:otherwise> 28 已发货 29 </c:otherwise> 30 </c:choose> 31 </td> 32 <td> 33 <a href="">详细</a> 34 </td> 35 </tr> 36 </c:forEach> 37 </table> 38 </c:if> 39 40 </body> 41 </html>
在线支付
支付过程图:
油条类
1 import java.io.UnsupportedEncodingException; 2 import java.security.MessageDigest; 3 import java.security.NoSuchAlgorithmException; 4 import java.util.Arrays; 5 6 public class PaymentUtil { 7 8 private static String encodingCharset = "UTF-8"; 9 10 /** 11 * 生成hmac方法 12 * 13 * @param p0_Cmd 业务类型 14 * @param p1_MerId 商户编号 15 * @param p2_Order 商户订单号 16 * @param p3_Amt 支付金额 17 * @param p4_Cur 交易币种 18 * @param p5_Pid 商品名称 19 * @param p6_Pcat 商品种类 20 * @param p7_Pdesc 商品描述 21 * @param p8_Url 商户接收支付成功数据的地址 22 * @param p9_SAF 送货地址 23 * @param pa_MP 商户扩展信息 24 * @param pd_FrpId 银行编码 25 * @param pr_NeedResponse 应答机制 26 * @param keyValue 商户密钥 27 * @return 28 */ 29 public static String buildHmac(String p0_Cmd,String p1_MerId, 30 String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat, 31 String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId, 32 String pr_NeedResponse,String keyValue) { 33 StringBuilder sValue = new StringBuilder(); 34 // 业务类型 35 sValue.append(p0_Cmd); 36 // 商户编号 37 sValue.append(p1_MerId); 38 // 商户订单号 39 sValue.append(p2_Order); 40 // 支付金额 41 sValue.append(p3_Amt); 42 // 交易币种 43 sValue.append(p4_Cur); 44 // 商品名称 45 sValue.append(p5_Pid); 46 // 商品种类 47 sValue.append(p6_Pcat); 48 // 商品描述 49 sValue.append(p7_Pdesc); 50 // 商户接收支付成功数据的地址 51 sValue.append(p8_Url); 52 // 送货地址 53 sValue.append(p9_SAF); 54 // 商户扩展信息 55 sValue.append(pa_MP); 56 // 银行编码 57 sValue.append(pd_FrpId); 58 // 应答机制 59 sValue.append(pr_NeedResponse); 60 61 return PaymentUtil.hmacSign(sValue.toString(), keyValue); 62 } 63 64 /** 65 * 返回校验hmac方法 66 * 67 * @param hmac 支付网关发来的加密验证码 68 * @param p1_MerId 商户编号 69 * @param r0_Cmd 业务类型 70 * @param r1_Code 支付结果 71 * @param r2_TrxId 易宝支付交易流水号 72 * @param r3_Amt 支付金额 73 * @param r4_Cur 交易币种 74 * @param r5_Pid 商品名称 75 * @param r6_Order 商户订单号 76 * @param r7_Uid 易宝支付会员ID 77 * @param r8_MP 商户扩展信息 78 * @param r9_BType 交易结果返回类型 79 * @param keyValue 密钥 80 * @return 81 */ 82 public static boolean verifyCallback(String hmac, String p1_MerId, 83 String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt, 84 String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid, 85 String r8_MP, String r9_BType, String keyValue) { 86 StringBuilder sValue = new StringBuilder(); 87 // 商户编号 88 sValue.append(p1_MerId); 89 // 业务类型 90 sValue.append(r0_Cmd); 91 // 支付结果 92 sValue.append(r1_Code); 93 // 易宝支付交易流水号 94 sValue.append(r2_TrxId); 95 // 支付金额 96 sValue.append(r3_Amt); 97 // 交易币种 98 sValue.append(r4_Cur); 99 // 商品名称 100 sValue.append(r5_Pid); 101 // 商户订单号 102 sValue.append(r6_Order); 103 // 易宝支付会员ID 104 sValue.append(r7_Uid); 105 // 商户扩展信息 106 sValue.append(r8_MP); 107 // 交易结果返回类型 108 sValue.append(r9_BType); 109 String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue); 110 return sNewString.equals(hmac); 111 } 112 113 /** 114 * @param aValue 115 * @param aKey 116 * @return 117 */ 118 public static String hmacSign(String aValue, String aKey) { 119 byte k_ipad[] = new byte[64]; 120 byte k_opad[] = new byte[64]; 121 byte keyb[]; 122 byte value[]; 123 try { 124 keyb = aKey.getBytes(encodingCharset); 125 value = aValue.getBytes(encodingCharset); 126 } catch (UnsupportedEncodingException e) { 127 keyb = aKey.getBytes(); 128 value = aValue.getBytes(); 129 } 130 131 Arrays.fill(k_ipad, keyb.length, 64, (byte) 54); 132 Arrays.fill(k_opad, keyb.length, 64, (byte) 92); 133 for (int i = 0; i < keyb.length; i++) { 134 k_ipad[i] = (byte) (keyb[i] ^ 0x36); 135 k_opad[i] = (byte) (keyb[i] ^ 0x5c); 136 } 137 138 MessageDigest md = null; 139 try { 140 md = MessageDigest.getInstance("MD5"); 141 } catch (NoSuchAlgorithmException e) { 142 143 return null; 144 } 145 md.update(k_ipad); 146 md.update(value); 147 byte dg[] = md.digest(); 148 md.reset(); 149 md.update(k_opad); 150 md.update(dg, 0, 16); 151 dg = md.digest(); 152 return toHex(dg); 153 } 154 155 public static String toHex(byte input[]) { 156 if (input == null) 157 return null; 158 StringBuffer output = new StringBuffer(input.length * 2); 159 for (int i = 0; i < input.length; i++) { 160 int current = input[i] & 0xff; 161 if (current < 16) 162 output.append("0"); 163 output.append(Integer.toString(current, 16)); 164 } 165 166 return output.toString(); 167 } 168 169 /** 170 * 171 * @param args 172 * @param key 173 * @return 174 */ 175 public static String getHmac(String[] args, String key) { 176 if (args == null || args.length == 0) { 177 return (null); 178 } 179 StringBuffer str = new StringBuffer(); 180 for (int i = 0; i < args.length; i++) { 181 str.append(args[i]); 182 } 183 return (hmacSign(str.toString(), key)); 184 } 185 186 /** 187 * @param aValue 188 * @return 189 */ 190 public static String digest(String aValue) { 191 aValue = aValue.trim(); 192 byte value[]; 193 try { 194 value = aValue.getBytes(encodingCharset); 195 } catch (UnsupportedEncodingException e) { 196 value = aValue.getBytes(); 197 } 198 MessageDigest md = null; 199 try { 200 md = MessageDigest.getInstance("SHA"); 201 } catch (NoSuchAlgorithmException e) { 202 e.printStackTrace(); 203 return null; 204 } 205 return toHex(md.digest(value)); 206 207 } 208 209 // public static void main(String[] args) { 210 // System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp杩?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t")); 211 // } 212 }
控制层servlet
1 public class ControllerServlet extends HttpServlet { 2 private BusinessService s = new BusinessServiceImpl(); 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 String op = request.getParameter("op"); 6 if("payUI".equals(op)){ 7 payUI(request,response); 8 }else if("pay".equals(op)){ 9 pay(request,response); 10 }else if("showMyOrders".equals(op)){ 11 showMyOrders(request,response); 12 } 13 } 14 //支付:准备数据 15 private void pay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 16 String ordersnum = request.getParameter("ordersnum"); 17 String money = request.getParameter("money"); 18 19 String pd_FrpId = request.getParameter("pd_FrpId");//支付通道 20 21 String p0_Cmd = "Buy"; 22 String p1_MerId = "10001126856";//在第三方申请的编号 23 String p2_Order = ordersnum; 24 String p3_Amt = money; 25 String p4_Cur = "CNY"; 26 String p5_Pid = "aaa"; 27 String p6_Pcat = "bbb"; 28 String p7_Pdesc = "ccc"; 29 String p8_Url = "http://localhost:8080/day23_00_bookstore/servlet/PaymentResponse"; 30 String p9_SAF = "1"; 31 String pa_MP = ""; 32 String pr_NeedResponse = "1"; 33 String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl"); 34 request.setAttribute("p0_Cmd",p0_Cmd ); 35 request.setAttribute("p1_MerId",p1_MerId ); 36 request.setAttribute("p2_Order",p2_Order ); 37 request.setAttribute("p3_Amt",p3_Amt ); 38 request.setAttribute("p4_Cur",p4_Cur ); 39 request.setAttribute("p5_Pid",p5_Pid ); 40 request.setAttribute("p6_Pcat",p6_Pcat ); 41 request.setAttribute("p7_Pdesc",p7_Pdesc ); 42 request.setAttribute("p8_Url",p8_Url ); 43 request.setAttribute("p9_SAF",p9_SAF ); 44 request.setAttribute("pa_MP",pa_MP ); 45 request.setAttribute("pd_FrpId",pd_FrpId ); 46 request.setAttribute("pr_NeedResponse",pr_NeedResponse ); 47 request.setAttribute("hmac",hmac ); 48 request.getRequestDispatcher("/sure.jsp").forward(request, response); 49 } 50 //转向支付页面 51 private void payUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 52 String ordersnum = request.getParameter("ordersnum"); 53 Orders o = s.findOrdersByNum(ordersnum); 54 request.setAttribute("o", o); 55 request.getRequestDispatcher("/pay.jsp").forward(request, response); 56 } 57 //生成订单,然后转向选择银行页面 58 private void genOrders(HttpServletRequest request, 59 HttpServletResponse response) throws ServletException, IOException{ 60 //判断用户是否登录 61 HttpSession session = request.getSession(); 62 Customer c = (Customer) session.getAttribute("customer"); 63 if(c==null){ 64 response.getWriter().write("<script type='text/javascript'>alert('请先登录')</script>"); 65 response.setHeader("Refresh", "0;URL="+request.getContextPath()+"/login.jsp"); 66 return; 67 } 68 //把购物车---->订单 69 Cart cart = (Cart)session.getAttribute("cart"); 70 Orders os = new Orders(); 71 String ordersnum = System.nanoTime()+""; 72 os.setOrdersnum(ordersnum); 73 os.setMoney(cart.getTotalMoney()); 74 os.setNum(cart.getTotalNum()); 75 os.setCustomer(c); 76 //把购物项---->订单项 77 Map<String, CartItem> items = cart.getItems(); 78 for(Map.Entry<String, CartItem> me:items.entrySet()){ 79 OrdersItem oitem = new OrdersItem(); 80 oitem.setId(UUID.randomUUID().toString()); 81 oitem.setNum(me.getValue().getNum()); 82 oitem.setMoney(me.getValue().getPrice()); 83 oitem.setBook(me.getValue().getBook()); 84 os.getItems().add(oitem); 85 } 86 //生成订单 87 s.saveOrders(os); 88 //转向付款页面:把订单号传过去 89 response.sendRedirect(request.getContextPath()+"/servlet/ControllerServlet?op=payUI&ordersnum="+ordersnum); 90 } 91 92 public void doPost(HttpServletRequest request, HttpServletResponse response) 93 throws ServletException, IOException { 94 doGet(request, response); 95 } 96 97 }
响应
1 import java.io.IOException; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 import com.itheima.domain.Orders; 9 import com.itheima.service.BusinessService; 10 import com.itheima.service.impl.BusinessServiceImpl; 11 import com.itheima.util.PaymentUtil; 12 //接受支付结果的处理 13 public class PaymentResponse extends HttpServlet { 14 private BusinessService s = new BusinessServiceImpl(); 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 String p1_MerId = request.getParameter("p1_MerId"); 18 String r0_Cmd= request.getParameter("r0_Cmd"); 19 String r1_Code= request.getParameter("r1_Code");//1代表成功 20 String r2_TrxId= request.getParameter("r2_TrxId"); 21 String r3_Amt= request.getParameter("r3_Amt"); 22 String r4_Cur= request.getParameter("r4_Cur"); 23 String r5_Pid= request.getParameter("r5_Pid"); 24 String r6_Order= request.getParameter("r6_Order");//订单号 25 String r7_Uid= request.getParameter("r7_Uid"); 26 String r8_MP= request.getParameter("r8_MP"); 27 String r9_BType= request.getParameter("r9_BType");//为“1”: 浏览器重定向;为“2”: 服务器点对点通讯. 28 String hmac= request.getParameter("hmac"); 29 //验证信息的正确性 30 boolean b = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl"); 31 if(b){ 32 if("1".equals(r1_Code)){ 33 //支付成功 34 if("2".equals(r9_BType)){ 35 response.getWriter().write("success"); 36 } 37 //更改订单的状态 38 Orders o = s.findOrdersByNum(r6_Order); 39 if(o==null){ 40 response.getWriter().write("没有改订单"); 41 return; 42 } 43 o.setStatus(1); 44 s.updateOrders(o); 45 response.getWriter().write("<script type='text/javascript'>alert('支付成功')</script>"); 46 response.setHeader("Refresh", "0;URL="+request.getContextPath()); 47 }else{ 48 response.getWriter().write("支付失败!请与网站联系"); 49 } 50 }else{ 51 response.getWriter().write("返回的信息有误,请与网站联系"); 52 } 53 } 54 55 public void doPost(HttpServletRequest request, HttpServletResponse response) 56 throws ServletException, IOException { 57 doGet(request, response); 58 } 59 60 }
视图层
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>在线支付</title> 7 8 <meta http-equiv="pragma" content="no-cache"> 9 <meta http-equiv="cache-control" content="no-cache"> 10 <meta http-equiv="expires" content="0"> 11 <!-- 12 <link rel="stylesheet" type="text/css" href="styles.css"> 13 --> 14 15 </head> 16 17 <body> 18 <form action="${pageContext.request.contextPath}/servlet/ControllerServlet?op=pay" method="post"> 19 <table width="60%"> 20 <tr> 21 <td bgcolor="#F7FEFF" colspan="4"> 22 订单号:<INPUT TYPE="text" NAME="ordersnum" value="${o.ordersnum}" readonly="readonly"> 23 支付金额:<INPUT TYPE="text" NAME="money" size="6" value="0.01" readonly="readonly">元 24 </td> 25 </tr> 26 <tr><td><br/></td></tr> 27 <tr> 28 <td>请您选择在线支付银行</td> 29 </tr> 30 <tr> 31 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="CMBCHINA-NET">招商银行 </td> 32 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="ICBC-NET">工商银行</td> 33 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="ABC-NET">农业银行</td> 34 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="CCB-NET">建设银行 </td> 35 </tr> 36 <tr> 37 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="CMBC-NET">中国民生银行总行</td> 38 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="CEB-NET" >光大银行 </td> 39 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="BOCO-NET">交通银行</td> 40 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="SDB-NET">深圳发展银行</td> 41 </tr> 42 <tr> 43 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="BCCB-NET">北京银行</td> 44 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="CIB-NET">兴业银行 </td> 45 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="SPDB-NET">上海浦东发展银行 </td> 46 <td><INPUT TYPE="radio" NAME="pd_FrpId" value="ECITIC-NET">中信银行</td> 47 </tr> 48 <tr><td><br/></td></tr> 49 <tr> 50 <td><INPUT TYPE="submit" value="确定支付"></td> 51 </tr> 52 </table> 53 54 </form> 55 </body> 56 </html>
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 <html> 3 <head> 4 <title>title</title> 5 6 <meta http-equiv="pragma" content="no-cache"> 7 <meta http-equiv="cache-control" content="no-cache"> 8 <meta http-equiv="expires" content="0"> 9 <!-- 10 <link rel="stylesheet" type="text/css" href="styles.css"> 11 --> 12 13 </head> 14 15 <body> 16 <form id="f1" action="https://www.yeepay.com/app-merchant-proxy/node" method="post"> 17 <input type="hidden" name="p0_Cmd" value="${p0_Cmd}"/> 18 <input type="hidden" name="p1_MerId" value="${p1_MerId}"/> 19 <input type="hidden" name="p2_Order" value="${p2_Order}"/> 20 <input type="hidden" name="p3_Amt" value="${p3_Amt}"/> 21 <input type="hidden" name="p4_Cur" value="${p4_Cur}"/> 22 <input type="hidden" name="p5_Pid" value="${p5_Pid}"/> 23 <input type="hidden" name="p6_Pcat" value="${p6_Pcat}"/> 24 <input type="hidden" name="p7_Pdesc" value="${p7_Pdesc}"/> 25 <input type="hidden" name="p8_Url" value="${p8_Url}"/> 26 <input type="hidden" name="p9_SAF" value="${p9_SAF}"/> 27 <input type="hidden" name="pa_MP" value="${pa_MP}"/> 28 <input type="hidden" name="pd_FrpId" value="${pd_FrpId}"/> 29 <input type="hidden" name="pr_NeedResponse" value="${pr_NeedResponse}"/> 30 <input type="hidden" name="hmac" value="${hmac}"/> 31 </form> 32 <script type="text/javascript"> 33 window.onload=function(){ 34 document.getElementById("f1").submit(); 35 } 36 </script> 37 </body> 38 </html>
订单的查询和修改
控制层
1 public class ControllerServlet extends HttpServlet { 2 private BusinessService s = new BusinessServiceImpl(); 3 public void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 String op = request.getParameter("op"); 6 if("showMyOrders".equals(op)){ 7 showMyOrders(request,response); 8 } 9 } 10 //查看用户自己的订单 11 private void showMyOrders(HttpServletRequest request, 12 HttpServletResponse response) throws ServletException, IOException{ 13 HttpSession session = request.getSession(); 14 Customer c = (Customer) session.getAttribute("customer"); 15 if(c==null){ 16 response.getWriter().write("<script type='text/javascript'>alert('请先登录')</script>"); 17 response.setHeader("Refresh", "0;URL="+request.getContextPath()+"/login.jsp"); 18 return; 19 } 20 List<Orders> os = s.findOrdersByCustomer(c.getId()); 21 request.setAttribute("os", os); 22 request.getRequestDispatcher("/showOrders.jsp").forward(request, response); 23 } 24 public void doPost(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 doGet(request, response); 27 } 28 29 }
视图层
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ include file="/top.jsp"%> 3 <c:if test="${empty os}"> 4 您还没有下过单 5 </c:if> 6 <c:if test="${!empty os }"> 7 <h3>一个月的订单如下</h3> 8 <table border="1" width="438"> 9 <tr> 10 <th>订单号</th> 11 <th>金额</th> 12 <th>状态</th> 13 <th>操作</th> 14 </tr> 15 <c:forEach items="${os}" var="o" varStatus="vs"> 16 <tr class="${vs.index%2==0?'odd':'even'}"> 17 <td>${o.ordersnum}</td> 18 <td>${o.money}</td> 19 <td> 20 <c:choose> 21 <c:when test="${o.status==0}"> 22 未付款<a href="${pageContext.request.contextPath}/servlet/ControllerServlet?op=payUI&ordersnum=${o.ordersnum}">付款</a> 23 </c:when> 24 <c:when test="${o.status==1}"> 25 已付款 26 </c:when> 27 <c:otherwise> 28 已发货 29 </c:otherwise> 30 </c:choose> 31 </td> 32 <td> 33 <a href="">详细</a> 34 </td> 35 </tr> 36 </c:forEach> 37 </table> 38 </c:if> 39 40 </body> 41 </html>