Java Web Development Shopping cart function realization

Source: Internet
Author: User
Tags uuid java web

The shopping cart function realizes, the query three kinds of methods.

1. Use cookies to realize the shopping cart;

"Disadvantages":

Simple cookies to implement a shopping cart, such a shopping cart is not ideal, imagine if the client's browser to disable the cookie,

This way it will hang out here. 2. Use seeesion to realize shopping cart;

"Disadvantages":

Save the shopping cart information in session, this is only available in a conversation, if the user is not logged in, or after logging in, add a shopping cart, in the closing browser

Or log out, the previously added shopping cart will only hang off.

3. Use cookies and database (shopping cart information persistence) to achieve the shopping cart;

The main process:

A. User log in before the data flow: Users do not login to the system, the favorite items to add shopping cart, then this time, we can store the shopping cart information

To cookies, this involves adding cookies, modifying the operation, or adding the cookie if the cookie is not stored in the cookie before.

If there is a cookie in the cookie, then it is time to modify the cookie (this involves the user adding a cart to the same item multiple times).

B. User logon Data flow: After the user login, the system first thing to do is to obtain the corresponding cookies, if there is a relevant shopping cart cookies, then the cart

The information is persisted by the corresponding user, either added or modified. (Add action: This user's corresponding shopping cart if there is no corresponding information to add action; Modify operation: similar,

If there is a corresponding user's shopping cart information, modify the operation. After the user logs in, you can also add the shopping cart, but this is not added to the cookie, but is directly persisted to the database.

Note: The data that the user logs in to deal with the database.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Code section:

Note:

1 conf.iduona_cashticket_cookie_startname = "iduona_cashticket_";

  
  1/** 2 * User Login 3 * 4 * @author hongten 5 */6 public void Login () {7/user Login
  When recording, to read cookies, and the operation of persistent words, more login operation here omitted ....
  8 Peristshoppingcartwhenuserlogin (NewUser);      9} 10 11/** 12 * Add Shopping cart <br> * ============================================<br> 14 * User Login before:<br> 15 * Users in the selection of cash coupons, click on the cash coupons to add to the cart, the cash coupon information (cash voucher ID, purchase quantity) <br> 16 * Delivered to here, this time, backstage to do is Whether the same record is queried from the cookie, if there is the same record <br> 17 * then update the corresponding record; otherwise, add a new record <br> 18 * User Login after:<br> 19 * with When you log in, if you add a shopping cart operation, you do not need to save it to a cookie, but you can directly persist the cart information <br> * @throws Exception Public void AddToShoppingCart () throws Exception {if (Cashticket = = NULL | | Cashticket.getid () = NULL | | cashticket
 . GetId () < 1) {write ("Nullid"); } else if (q = = NULL | | q = = "") {27//purchase quantity, by default 1 q = string.valueof (1); /else {30//Read all cookies to cookie cookies[] = servletactioncontext.getrequest (). GE
 Tcookies (); if (cookies = = NULL | | Cookies.length < 0) {33//No cookie System.
 Out.println ("There is no cookie ...");                     /else {36//Determine whether the user is logged in to the getuserinsession () = = null) {38
 Boolean flag = true; The C:cookies (Cookie) {c.getname (). Equals (Conf.iduona_cashticke                             T_cookie_startname + Cashticket.getid ()) {41//Description Existing cookies have corresponding cookies, update operation 42
 Integer OldValue = integer.valueof (C.getvalue ());
 The Integer newvalue = integer.valueof (OldValue + integer.valueof (q));
 Fixcookie (c, newvalue.tostring (). Trim ());
 Flag = false;    46                     {47} 48//Description Existing Cookies do not have a corresponding cookie, add Operation 49  if (flag) {Addcookie (Conf.iduona_cashticket_cookie_startname + cashticket.getid (),
 Q.trim ());                     51} 52 53//================================================== 54
 For testing, read all Cookies Readshoppingcartfromcookie (); A//================================================== write ("Success")
 ; /else {60///If the user is logged in, stating that session exists user, then the persistent shopping cart information Cashtick
 ET cashtickettemp = Cashticketservice.get (Cashticket.getid ());                         if (Shoppingcartservice.isexistuserandcashticket (Getuserinsession (), cashtickettemp)) {63 ShoppingCart Oldshoppingcart = Shoppingcartservice.getbyuserandcashticket (getuserinsesSion (), cashtickettemp);
 Oldshoppingcart.setamount (Oldshoppingcart.getamount () + integer.valueof (q)); (Shoppingcartservice.update (Oldshoppingcart)) {Write ("Succe
 SS "); Shoppingcarttemp} else {ShoppingCart =
 New ShoppingCart ();
 Shoppingcarttemp.setamount (integer.valueof (q));
 Shoppingcarttemp.setuser (Getuserinsession ());
 Shoppingcarttemp.setcashticket (cashtickettemp);
 Shoppingcarttemp.setcreatetime (New Date ());
 Shoppingcarttemp.setstatustype (statustype.positive);
 Shoppingcarttemp.setuuid (Uuid.randomuuid (). toString ()); The IF (Shoppingcartservice.save (shoppingcarttemp)) {Write ("succes S ");
 78} 79} 80} 81} 82} 83} 8 4 85/** 86 * Read the cart information from the cookie * * @throws Exception * @return Publ IC void Readshoppingcartfromcookie () throws Exception {System.out.println ("==================================
 ====================");
 cookies[Cookie] = Servletactioncontext.getrequest (). GetCookies (); if (cookies = null | | Cookies.length < 0) {//System.out.println ("There is no cookie.")
 ."); 96//No Cookie c:cookies} else {The for (cookie) {System.out.
println ("haha there are many cookies:" + c.getname () + "" + C.getvalue ());      100} 101} 102} 103 104/** 105 * Add Cookie Operation # * @param name 108 * Cookie Name 109 * @param value $ * CookIE's value-*/112 public void Addcookie (string name, String value) {113 Cookie = new Cookie (nam
E.trim (), Value.trim ()); 114 Cookie.setmaxage (2 * 60 * 60 * 1000);//set to 2 clock Servletactioncontext.getresponse (). Addcookie (Cookie
);      116} 117 118/** 119 * Update Cookie Operation * 121 * @param c 122 * Cookie to be modified 123         * Value of @param value 124 * Modified Cookie * * 126 public void Fixcookie (cookie C, String value) {127
C.setvalue (Value.trim ());
128 C.setmaxage (2 * 60 * 60 * 1000);//set to 2 clock 129 servletactioncontext.getresponse (). Addcookie (c); 130} 131 132/** 133 * When the user is logged in, the shopping cart information in the cookie is persisted and updated to the user's cart information 134 * * 135 public void Peristshoppin Gcartwhenuserlogin (user user) {136 if (null!= User) {137 Cookie cookies[] = servletactioncontext.ge
Trequest (). GetCookies (); 138 if (cookies!= null) {139 for (CoOkie c:cookies) {140 if (c.getname (). StartsWith (Conf.iduona_cashticket_cookie_startname)) {141 Get the name of the cookie: "Iduona_cashticket_45" and the value of the cookie: "" "" "" "" "" ""
Tname ();
143 Integer amount = integer.valueof (integer.valueof (C.getvalue ()) +integer.valueof (q));
144 Integer ct_id = integer.valueof (name.substring (Name.lastindexof ("_") + 1));
145 Cashticket temp = cashticketservice.get (ct_id);
146 ShoppingCart shoppingcarttemp = new ShoppingCart (); 147 if (null!= temp) {148 if (Shoppingcartservice.isexistuserandcash Ticket (user, temp)) {149//update operation ShoppingCart OLDSH
Oppingcart = shoppingcartservice.getbyuserandcashticket (user, temp); 151 Oldshoppingcart.setamount (Amount);
152 Shoppingcartservice.update (Oldshoppingcart);                                 153} else {154//otherwise save record 155
Shoppingcarttemp.setamount (amount);
156 shoppingcarttemp.setuser (user);
157 Shoppingcarttemp.setcashticket (temp);
158 Shoppingcarttemp.setcreatetime (New Date ());
159 Shoppingcarttemp.setstatustype (statustype.positive);
160 Shoppingcarttemp.setuuid (Uuid.randomuuid (). toString ());
161 Shoppingcartservice.save (SHOPPINGCARTTEMP);                 162} 163} 164} 165} 166
Remove all cash coupons from Cookies 167 removeallcookies (); 168} 169} 170} 171 172/** 173 * Remove AllCash Coupon Cookies Operation 174 */175 public void removeallcookies () {176 Cookie cookies[] = Servletactioncontext.getr
Equest (). GetCookies (); 177 if (cookies = null | | Cookies.length < 0) {178//no Cookie 179 System.out.println
("There is no cookie ...");                 180} else {181 System.out.println ("Start deletion of cookies ..."); for (Cookie c:cookies) {183 if (C.getname (). StartsWith (Conf.iduona_cashticket_cookie_startname)) {184 C.setmaxage (
0)//set to 0 185 servletactioncontext.getresponse (). Addcookie (c); 186} 187} 188} 189}

This is part of the code ....

Effect:

User is not logged in

After the user has logged in:

The situation inside the database:

Pre-logon data

Related Article

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.