Javaweb Book Mall Design Order Module (5) _java

Source: Internet
Author: User
Tags hmac uuid

This article is aimed at the Javaweb Book Mall in the Order module research,

1. Create related class

Domain
Order
OrderItem
Dao:orderdao
Service:orderservice
Web.servlete:OrderServlet

/**
 * Order Entry class
 *
/public class OrderItem {
 private String iid;
 private int count;//number
 private double subtotal;//subtotal
 private order order;//owning orders
 private book book;//books to buy
}
/**
 * Order class
/public class orders {
 private String oid;
 Private Date ordertime;//single time
 private double total;//total
 private int state;//order status There are four kinds: 1 unpaid 2 paid but not shipped 3 shipped but not confirmed receipt 4 confirmed transaction successful
 private User owner;//order owner
 Private String address;//delivery address

 private list<orderitem> orderitemlist;//all entries under current order 
}


public class Orderdao {private Queryrunner QR = new Txqueryrunner (); /** * Add orders * @param order * */public void AddOrder (ordering order) {try {String sql = ' INSERT INTO orders values
   (?,?,?,?,?,?)";
   * * Processing util date into SQL Timestamp/Timestamp Timestamp = new Timestamp (Order.getordertime (). GetTime ()); Object[] params = {order.getoid (), timestamp, order.gettotal (), Order.getstate (), Order.getowner (). Getuid (), Ord
   Er.getaddress ()};
  Qr.update (sql, params);
  catch (SQLException e) {throw new RuntimeException (e);
  /** * Insert Order Entry * @param orderitemlist */public void addorderitemlist (list<orderitem> orderitemlist) {
   /** * Queryrunner class batch (String sql, object[][] params) * Where params is a multiple one-dimensional array!
   * Each one-dimensional array is executed with SQL once, multiple one-dimensional arrays are executed multiple times/try {String sql = INSERT into OrderItem values (?,?,?,?,?); * * Convert Orderitemlist to two-d array * Convert a OrderItem object into a one-dimensional array/object[][] params = new Object[orderitemlist.sizE () []; Iterate through the orderitemlist, using each OrderItem object to assign a value for each one-dimensional array in params (int i = 0; i < orderitemlist.size (); i++) {OrderItem I
    TEM = Orderitemlist.get (i); Params[i] = new Object[]{item.getiid (), Item.getcount (), Item.getsubtotal (), Item.getorder (). Getoid (), ITEM.G 
   Etbook (). Getbid ()};
  Qr.batch (sql, params);//Execute batch} catch (SQLException e) {throw new RuntimeException (e); /** * by UID Query order * @param UID * @return/public list<order> findbyuid (String uid) {/* 1. Through U ID queries all list<order> * 2 for the current user. Loop through each order, load all of his OrderItem/try {* * * 1. Get all orders for current user */String sql = "SELECT * FROM Orders where"
   Uid=? ";

   list<order> orderlist = qr.query (sql, New beanlisthandler<order> (Order.class), UID); * * 2.

   Loop through each order, load it all its own orders for it (ordered Order:orderlist) {loadorderitems (order), or add all of its orders entries to the ordering object} * * 3.
  Return Order list * * orderlist; } catch (SQLException e) {throw new RuntimeException (e); }/** * Load the specified order all order entries * @param orders * @throws SQLException/private void Loadorderitems (ordering) th Rows SQLException {* * * query two tables: OrderItem, book/String sql = "SELECT * from OrderItem i, book B where i.bid=b.b
  ID and oid=? "; * * Because a row of result set corresponds to no longer a javabean, so can not use Beanlisthandler, but Maplisthandler * * * list<map<string,object>> mapli
  st = qr.query (SQL, New Maplisthandler (), order.getoid ()); * * Maplist is multiple map, each map corresponds to one row result set * Row: * {iid=c7ad5492f27d492189105fb50e55cbb6, count=2, subtotal=60.0, Oid=1ae8a7
   0354c947f8b81b80ada6783155, bid=7, bname= proficient hibernate,price=30.0, author= Zhang Weichen, image=book_img/8991366-1_l.jpg, cid=2} * ... * We need to use a map to generate two objects: OrderItem, book, and then establish the relationship between the two (set the book to OrderItem)/* * Loop through each map, use map to generate two objects, and then build
  Relationship (the end result of a orderitem), OrderItem to save the list<orderitem> orderitemlist = Toorderitemlist (maplist); Order.setorderitemlist (OrderitemliST); /** * Converts each map in maplist to two objects and establishes a relationship * @param maplist * @return * * Private list<orderitem> Toorderitemlist (list<map<string, object>> maplist)
  {list<orderitem> orderitemlist = new arraylist<orderitem> ();
   for (map<string,object> map:maplist) {OrderItem item = Toorderitem (MAP);
  Orderitemlist.add (item);
 return orderitemlist; /** * Converts a map to a OrderItem object * @param map * @return/private OrderItem Toorderitem (map<string, Object&gt ;
  Map) {OrderItem OrderItem = Commonutils.tobean (map, Orderitem.class);
  Book book = Commonutils.tobean (map, Book.class);
  Orderitem.setbook (book);
 return orderitem; /** * Load Order * @param OID * @return/Public order load (String oid) {try {* * * 1. Get all orders from current user *
   /String sql = "SELECT * from Orders where oid=?";

   order = qr.query (sql, New beanhandler<order> (Order.class), OID); * * 2. Load all of its entries for order * * LoadorderiteMS (order); * * 3.
  Returns order list * *;
  catch (SQLException e) {throw new RuntimeException (e);  /** * Query order status through OID * @param oid * @return/public int getstatebyoid (string oid) {try {String sql =
   "Select state from Orders where oid=?";
  Return (Integer) qr.query (SQL, New Scalarhandler (), OID);
  catch (SQLException e) {throw new RuntimeException (e);
  /** * Modify Order Status * @param oid * @param state * @return/public void Updatestate (String oid, int state) { try {String sql = ' Update orders set state=?
   where oid=? ";
  Qr.update (SQL, State, OID);
  catch (SQLException e) {throw new RuntimeException (e);

 }
 }
}
public class OrderService {private Orderdao Orderdao = new Orderdao (); /** * Payment Method * @param oid/public void Zhifu (String oid) {/* 1. Get the status of the order * * If the status is 1, then execute the following code * * If the status is not
  is 1, then this method does nothing */int state = Orderdao.getstatebyoid (OID);
  if (state = = 1) {//Modify order Status of 2 Orderdao.updatestate (OID, 2); }/** * Add order * need to process transaction * @param orders/public void Add (ordering) {try {//Open transaction Jdbcutils.begin

   Transaction (); Orderdao.addorder (order);//Insert Orders Orderdao.addorderitemlist (Order.getorderitemlist ());//Insert all entries in the order//COMMIT TRANSACTION Jdbcuti
  Ls.committransaction ();
   catch (Exception e) {//ROLLBACK TRANSACTION try {jdbcutils.rollbacktransaction ();
  The catch (SQLException E1) {} throw new RuntimeException (e); }/** * My order * @param UID * @return/public list<order> myorders (String uid) {return Orderdao.fin
 Dbyuid (UID); /** * Load Order * @param OID * @return */Public orders load (String oid) {return orDerdao.load (OID);
  /** * Confirm Receipt * @param oid * @throws orderexception/public void confirm (String oid) throws Orderexception { * * 1. Check order status, if not 3, throw an exception/int state = Orderdao.getstatebyoid (OID);/Get order status if (state!= 3) throw new Orderexception ("Order confirmation Failure, you are not a good thing!

  "); * * 2.
 Modify order Status of 4, indicating successful transaction/Orderdao.updatestate (OID, 4);

 }
}
public class Orderservlet extends Baseservlet {private OrderService OrderService = new OrderService (); /** * Payment to the bank * * @param request * @param response * @return * @throws servletexception * @throws ioexceptio n */Public String Zhifu (httpservletrequest request, httpservletresponse response) throws Servletexception, ioexcept
  Ion {Properties Props = new properties ();
  InputStream input = This.getclass (). getClassLoader (). getResourceAsStream ("merchantinfo.properties");
  Props.load (input);
  * * Prepare 13 parameters */String p0_cmd = "buy";
  String P1_merid = Props.getproperty ("P1_merid");
  String P2_order = Request.getparameter ("oid");
  String P3_amt = "0.01";
  String p4_cur = "CNY";
  String p5_pid = "";
  String p6_pcat = "";
  String P7_pdesc = "";
  String P8_url = Props.getproperty ("P8_url");
  String P9_saf = "";
  String pa_mp = "";
  String pd_frpid = Request.getparameter ("Pd_frpid");

  String pr_needresponse = "1"; * * Calculate HMAC/String keyvalue = Props.getproperty ("KeyValue"); 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, keyvalue);
  * * Connect the URL of the PO and 13+1 parameters * * * StringBuilder URL = new StringBuilder (props.getproperty ("url"));
  Url.append ("? p0_cmd="). Append (P0_cmd);
  Url.append ("&p1_merid="). Append (P1_merid);
  Url.append ("&p2_order="). Append (P2_order);
  Url.append ("&p3_amt="). Append (P3_amt);
  Url.append ("&p4_cur="). Append (P4_cur);
  Url.append ("&p5_pid="). Append (P5_pid);
  Url.append ("&p6_pcat="). Append (P6_pcat);
  Url.append ("&p7_pdesc="). Append (P7_pdesc);
  Url.append ("&p8_url="). Append (P8_url);
  Url.append ("&p9_saf="). Append (P9_SAF);
  Url.append ("&pa_mp="). Append (PA_MP);
  Url.append ("&pd_frpid="). Append (Pd_frpid);
  Url.append ("&pr_needresponse="). Append (Pr_needresponse);

  Url.append ("&hmac="). Append (HMAC); System.out.println(URL);

  * * Redirect to Yi Po/response.sendredirect (Url.tostring ());
 return null;
  /** * This method is a valuable callback method we have to judge the call this method is not Yi Bao! * @param Request * @param response * @return * @throws servletexception * @throws ioexception * * Public St  Ring-Back (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {* * * 1.
  Get one + 1 */String P1_merid = Request.getparameter ("P1_merid");
  String r0_cmd = Request.getparameter ("R0_cmd");
  String R1_code = Request.getparameter ("R1_code");
  String R2_trxid = Request.getparameter ("R2_trxid");
  String R3_amt = Request.getparameter ("R3_amt");
  String r4_cur = Request.getparameter ("R4_cur");
  String r5_pid = Request.getparameter ("R5_pid");
  String R6_order = Request.getparameter ("R6_order");
  String R7_uid = Request.getparameter ("R7_uid");
  String R8_MP = Request.getparameter ("R8_mp");

  String R9_btype = Request.getparameter ("R9_btype"); String HMAC = Request.getparameter ("HMAC "); * * 2.
   Check if the visitor is Yeepay!
  * * Properties Props = new properties ();
  InputStream input = This.getclass (). getClassLoader (). getResourceAsStream ("merchantinfo.properties");
  Props.load (input);

  String keyvalue = Props.getproperty ("KeyValue");  boolean bool = 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, keyvalue); if (!bool) {//If checksum fails Request.setattribute ("MSG", "You are not a good thing!")
   ");
  return "f:/jsps/msg.jsp"; } * * 3.

  Obtain status orders, determine whether to modify the order status, and add points, such as business Operations/Orderservice.zhifu (R6_order), or the database can be operated, or may not operate! * * 4.
  To determine the current callback mode * If it is a point-to-point, you need to give back the string starting with success/if (R9_btype.equals ("2")) {Response.getwriter (). Print ("Success"); } * * 5. Save success information, forward to msg.jsp * * Request.setattribute ("msg", "Pay success!") Wait for seller to ship!
  You slowly wait ~ ");
 return "f:/jsps/msg.jsp"; /** * Confirm Receipt * * @param request * @param response * @return * @throws servletexception * @throws IOException */Public String confirm (HttpServletRequest request, httpservletresponse response) throws Servletexception
   , IOException {* * 1. Get OID parameter 2. Invoke Service method > If there is an exception, save the exception information and forward to msg.jsp 3.
  * Save success information, forward to msg.jsp */String oid = Request.getparameter ("oid");
   try {orderservice.confirm (OID); Request.setattribute ("msg", "Congratulations, trading success!")
  ");
  catch (Orderexception e) {request.setattribute ("msg", E.getmessage ());
 Return to "f:/jsps/msg.jsp"; /** * Load Order * @param request * @param response * @return * @throws servletexception * @throws ioexcept Ion */Public String load (httpservletrequest request, httpservletresponse response) throws Servletexception, Ioexcep
   tion {/* * 1. Get OID parameter 2. Use OID to invoke the service method to get order 3. * Save to request field, forward to/jsps/order/desc.jsp/Request.setattribute ("Order", Orderservice.load ("Oi
  D "));
 return "f:/jsps/order/desc.jsp"; /** * My order * @param request * @param RESPONSE * @return * @throws servletexception * @throws ioexception/public String myorders (HttpServletRequest reque
   St, httpservletresponse response) throws Servletexception, IOException {* * * 1. Gets the current user from session, and then obtains its UID 2.
   * Use UID call orderservice#myorders (UID) to get all orders for that user List<order> 3.
  * Save the order list to the request field and forward to/jsps/order/list.jsp/user user = (User) request.getsession (). getattribute ("Session_user");
  list<order> orderlist = Orderservice.myorders (User.getuid ());
  Request.setattribute ("OrderList", orderlist);
 return "f:/jsps/order/list.jsp"; /** * Add order to use the car in session to generate an object * @param request * @param response * @return * @throws Servletexcepti On * @throws IOException */Public String Add (httpservletrequest request, httpservletresponse response) throws Ser
   Vletexception, IOException {/* 1. Get cart 2 from session. Use CART to generate order Object 3. Call the Service method to complete add orders 4. * Save order to request field, forward to/jsps/order/desc.jsp *///from session to get CArt Cart cart = (cart) request.getsession (). getattribute ("cart");
  Convert Cart to order object/* Create the object and set the property * Cart--> the order/order = new (); Order.setoid (Commonutils.uuid ());//Set number Order.setordertime (new Date ());//Set the next single time order.setstate (1);/set order status to 1,
  Represents the unpaid user user = (User) request.getsession (). getattribute ("Session_user"); Order.setowner (user)//Set order owner Order.settotal (cart.gettotal ())//Set the total of the order, get the total from cart * * Create order Entry Collection * * car
  Titemlist--> orderitemlist * * list<orderitem> orderitemlist = new arraylist<orderitem> (); Loops through all the cartitem in the cart, creates the OrderItem object with each Cartitem object, and adds it to the collection for (Cartitem CartItem:cart.getCartItems ()) {Orderite M oi = new OrderItem ()///Create Order Entry Oi.setiid (Commonutils.uuid ());//Set the ID of the entry oi.setcount (Cartitem.getcount ());//Set Bar Purpose Quantity Oi.setbook (Cartitem.getbook ());//Set the book Oi.setsubtotal (Cartitem.getsubtotal ()) of the entry;//Set Subtotal Oi.setorder (order) for entries //Set up the owning order OrderitEmlist.add (OI);//Add the order entry to the collection}//Add all the order entries to the order order.setorderitemlist (orderitemlist);

  Empty the shopping cart cart.clear (); * * 3.
  Call OrderService Add Order */Orderservice.add (orders); * * 4.
  Save order to request field, forward to/jsps/order/desc.jsp * * Request.setattribute ("order");
 return "/jsps/order/desc.jsp";

 }
}

2. Generate Order

3. My order (check by user)

4. Load order (by ID)

5. Confirm Receipt

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.