Realization principle and code Writing of Java Web shopping cart function

Source: Internet
Author: User
Tags session id trim uuid java web

The current common web shopping cart implementation methods are mainly three kinds: 1. Use cookies to realize the shopping cart; 2. Use the session to realize the shopping cart; 3. Use cookies and database (shopping cart information persistence) to realize the shopping cart;

=========================================================================

analyze the pros and cons of these three approaches:

1. 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's going to miscarry here ...

2.session Save the shopping cart information, this is only available in a session, if the user is not logged in, or said to log in after the Add shopping cart, in the closing browser

or log out, before the addition of the shopping cart are all aborted ...

3. I would say this is the way ...

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. When a user logs in, the shopping cart can also be added, but this is not added to the cookie, but is persisted directly 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_";

/**  *  User Login  *   *  @author  hongten  */public void login ()  {     //User login, to read cookies, and the operation of persistent words, more login operation here omitted ....     
Peristshoppingcartwhenuserlogin (NewUser); &NBSP;&NBSP;&NBSP;&NBSP}/**  *  Add shopping cart <br>  * ========================================= ===<br>  *  user before login:<br>  *  when selecting a cash coupon, click on the cash coupon when adding the cart, the information of the cash coupon (the ID of the cash coupon, purchase quantity) is &LT;BR >  *  passed here, at this time, the background to do is to check out the cookie from the same record, if the same records <br>  *  to update the corresponding records; otherwise, add a new record < br>  *  User Login after:<br>  *  user login, if there is add shopping cart operation, then do not save to the cookie, but the direct persistence of the cart information <br>  *    *  @throws  exception  */public void addtoshoppingcart ()  throws  exception {    if  (cashticket == null | |  cashticket.getid ()  == null | |  cashticket.getid ()  < 1)  {&Nbsp;       write ("Nullid");     } else if  (q == null | |  q ==  "")  {        //  purchase quantity, by default 1  
       q = string.valueof (1);
    } else {        //  Read All Cookies         Cookie cookies[] = 
Servletactioncontext.getrequest (). GetCookies ();         if  (cookies == null | |  cookies.length < 0)  {             //  No Cookies             
System.out.println ("THERE&NBSP;IS&NBSP;NO&NBSP;ANY&NBSP;COOKIE&NBSP;.");         } else  {            //  Determine if the user is logged in    
         if  (Getuserinsession ()  == null)  {                 boolean 
flag = true;                 for  ( cookie c : cookies)  {                     if  (C.getname (). Equals (conf.iduona_cashticket_ Cookie_startname + cashticket.getid ())  {                         //  Note that cookies are available in existing cookies and update operations are performed                          integer oldvalue = integer.valueof (
C.getvalue ());                          integer newvalue = integer.valueof (oldValue + 
Integer.valueof (q));                   
      fixcookie (c, newvalue.tostring (). Trim ());                   
      flag = false;                   
  }                 }                 //  to indicate that there is no corresponding cookie in the existing cookies, add the Operation                  if  (flag)  {                     addcookie (
Conf.iduona_cashticket_cookie_startname + cashticket.getid (),  q.trim ());                 }                  // ================== ================================                  //  test, read all Cookies            
     readshoppingcartfromcookie ();                 // ==================================================         
        write ("Success");             } else {                 //  if the user logs in, the session exists user, This is the time to persist shopping cart information                 
Cashticket cashtickettemp = cashticketservice.get (Cashticket.getid ());                 if  ( Shoppingcartservice.isexistuserandcashticket (Getuserinsession (),  cashtickettemp))  {                      Shoppingcart oldshoppingcart = shoppingcartservice.getbyuserandcashticket (GetUSerinsession (),  cashtickettemp);                   
  oldshoppingcart.setamount (Oldshoppingcart.getamount ()  + integer.valueof (q));                      if  (Shoppingcartservice.update (Oldshoppingcart))  {                         
Write ("Success");                      }                 }  else {                     shoppingcart shoppingcarttemp = 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 ());                      if  (Shoppingcartservice.save (shoppingcarttemp))  {                         
Write ("Success");                   
  }                 }             }        &NBSP;&NBSP}    &nbsp}}/**  *  read shopping cart information from cookies  *   *  @throws   Exception  *  @return  */public void readshoppingcartfromcookie ()  throws  exception {    system.out.println ("======================================================");
    cookie cookies[] = servletactioncontext.getrequest (). GetCookies ();     if  (cookies == null | |  cookies.length < 0)  {        // 
System.out.println ("THERE&NBSP;IS&NBSP;NO&NBSP;ANY&NBSP;COOKIE&NBSP;.");
        //  No Cookie     } else {         for  (cookie c : cookies)  {             system.out.println ("Haha there are &NBSP;MANY&NBSP;COOKIES&NBSP: " + c.getname ()  + "      " + 
C.getvalue ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}    &nbsp}}/**  *  add cookie Operation  *    *  @param  name   *            cookie's name  *  @param   Value  */public of value  *            cookie  void addcookie (string name, string value)  {    Cookie 
Cookie = new cookie (Name.trim (),  value.trim ());
    cookie.setmaxage (2 * 60 * 60 * 1000);//  set to 2 clock
    servletactioncontext.getresponse (). Addcookie (cookie); /**  *  Update cookie operations  *   *  @param  c  *              cookies to modify  *  @param  value  *              the value of the modified cookie  */Public void fixcookie (cookie  c, string value)  {    c.setvalue (value.trIm ());     c.setmaxage (2 * 60 * 60 * 1000);//  set to 2 clock  
   servletactioncontext.getresponse (). Addcookie (c); /**  *  When a user logs on, the shopping cart information in the cookie is persisted and updated to the user's cart information  */public void  Peristshoppingcartwhenuserlogin (User user)  {    if  (Null != user)  {        Cookie cookies[] = 
Servletactioncontext.getrequest (). GetCookies ();         if  (cookies != null)  {   
         for  (cookie c : cookies)  {                 if  ( C.getname (). StartsWith (Conf.iduona_cashticket_cookie_startname))  {                     //  gets the name of the cookie: "iduona_cashticket_45"   and  cookie value:  "21"                   
  string name = c.getname ();                   
  integer amount = integer.valueof (Integer.valueof (C.getvalue ()) +Integer.valueOf (q));                      integer ct_id = integer.valueof (Name.substring (Name.lastindexof ("_")  + 1)
);                   
  cashticket temp = cashticketservice.get (ct_id);                   &Nbsp; shoppingcart shoppingcarttemp = new shoppingcart ();                      if  (null != temp)  {                         if  ( Shoppingcartservice.isexistuserandcashticket (user, temp))  {                              //  Update Operations                              shoppingcart
 oldshoppingcart = shoppingcartservice.getbyuserandcashticket (user, temp);                             
Oldshoppingcart.setamount (amount);                   
          shoppingcartservice.update (OldShoppingCart);                          } else {                              //  otherwise save record                              shoppingcarttemp.setamount
(amount);                             shoppingcarttemp.setuser (user);                   
          shoppingcarttemp.setcashticket (temp);                   
          shoppingcarttemp.setcreatetime (New Date ());                              shoppingcarttemp.setstatustype (StatusType.POSITIVE
);                              shoppingcarttemp.setuuid (UUID.randomUUID ().
ToString ());                          
   shoppingcartservice.save (shoppingcarttemp);                          }                      }           
      }             }             //  Remove all cash coupons from cookies   
          removeallcookies ();
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}    &nbsp}}/**  *  remove all cash coupon cookies from operation  */public void removeallcookies ()  {    cookie cookies[] = servletactioncontext.getrequest (). GetCookies ();     if  (cookies == null | |
 cookies.length < 0)  {        //  No Cookies         system.out.println ("There is no any cookie
 . ");     } else {        system.out.println ("
Start removing cookies ... ");         for  (cookie c : cookies)  {             if  (C.getname (). StartsWith (Conf.iduona_ Cashticket_cookie_startname)  {                 c.setmaxage (0);//  set to 0                  servletactioncontext.getResponse (). Addcookie (c);             }          }    &nbsp}}



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



Java Shopping Cart Implementation code based on session and Cookie


1, the first abstract "shopping cart", by merchandise, shopping cart items, shopping cart three components.


package  com.pf.entity;
import  java.io.serializable; /** *  Products   (Food) *   @author &NBSP;&NBSP;PF * * public class  food   implements  serializable{ private int food_id ;      
private  string  food_name ;      public int  getfood_id ()  {     
   return food_id ; &NBSP;&NBSP;&NBSP;&NBSP}      public void  setfood_id ( int   food_id)  {        this . food_id  =
 food_id;
&NBSP;&NBSP;&NBSP;&NBSP}      public  string getfood_name ()  {
        return food_name ;     }      public void &nbSp;setfood_name (string food_name)  {        this . 
food_name  = food_name;
&NBSP;&NBSP;&NBSP;&NBSP}} package  com.pf.entity;
import  java.io.serializable; /** *   Shopping Cart Item *   @author &NBSP;&NBSP;PF * * * */public class  cartitem   implements  serializable{     private  Food  food 
;
     private int count ;      public  food getfood ()  {      
  return food ; &NBSP;&NBSP;&NBSP;&NBSP}      public void  setfood (Food food)  {        this . food  = food;   &NBSP;&NBSP;&NBSP}      public int  getcount ()  {&Nbsp;       return count ; &NBSP;&NBSP;&NBSP;&NBSP}      public void  setcount ( int   count)  {        this . count  = 
Count
&NBSP;&NBSP;&NBSP;&NBSP}}   package  com.pf.entity;
import  java.io.serializable;
import  java.util.arraylist;
import  java.util.list; /** *   Shopping Cart class *   @author &NBSP;&NBSP;PF_CQ * * * * * * public class  cart   implements  serializable{    List<CartItem>  list = 
New  arraylist<cartitem> ();      public  list<cartitem> getlist ()  {   
     return list ; &NBSP;&NBSP;&NBSP;&NBSP}      public void  setlist (List&Lt cartitem> list)  {        this . list 
 = list; &NBSP;&NBSP;&NBSP;&NBSP}      public void  addcartitem (CartItem  Item) {        for  (cartitem it :  list ) {            if  (It.getfood (). getfood_id () = = Item.getfood () getfood_id ()              
  return ; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         list .add (item
); &NBSP;&NBSP;&NBSP;&NBSP}      public void  removeitem (CartItem  Item) {        list .remove (item); &NBSP;&NBSP;&NBSP;&NBSP}       public void  clearcart () {&NBSP;&NBsp;      list .clear (); &NBSP;&NBSP;&NBSP;&NBSP}}



2, when the shopping cart is abstracted, create a session listener that is saved in a set of key-value pairs each time you create a session, and the next time you can get it through the session ID

package  com.pf.org;
import  java.util.hashmap;
import  java.util.map;
import  javax.servlet.http.httpsession;
import  javax.servlet.http.httpsessionevent;
import  javax.servlet.http.httpsessionlistener; /** * session  Listener *   @author &NBSP;&NBSP;PF * * * * */Public class  sessionlistener
  implements  httpsessionlistener {     //Session  Collection      public static  map<string,httpsession>  session_
Map = new  hashmap<string,httpsession> ();      /**      *   Create a  session       */     public void  sessioncreated (HttpSessionEvent  sessionevent)  {       string session_id= Sessionevent.getsession (). GetId ();        system. out .println ( ) ======  created a  session
,id  is &nbsp: " +session_id+ "  );         session_map .put (session_id, sessionevent.getsession
()); &NBSP;&NBSP;&NBSP;&NBSP}      /**      *   destroy       */     public void  sessiondestroyed ( httpsessionevent sessionevent)  {        session_map 
Remove (sessionevent.getsession ()); &NBSP;&NBSP;&NBSP;&NBSP}      /**      *   get   Session      *   @param   session_id      *    @return      */     public static   HttpSession Getsessionbyid (string session_id) {        return session_map
 .get (session_id); &NBSP;&NBSP;&NBSP;&NBSP}      /**      *   removal  
Session      *   @param   session_id      */      public static void  removesessionbyid (String session_id ) {        session_map .remove (session_id);     &NBSP}}



3. Next, create a class that can manipulate cookies


package  com.pf.org;
import  java.util.hashmap;
import  java.util.map;
import  javax.servlet.http.cookie;
import  javax.servlet.http.httpservletrequest;
import  javax.servlet.http.httpservletresponse; /** * web  tool   (  for Operation  cookie) *   @author &NBSP;&NBSP;PF * * */Public class   webutil {     /**      *   Add  
Cookie      *      *   @param   response      *   @param   name      *             Cookie  's name      *    @param   value      *        Value of      Cookie       *   @param   maxage      *             Cookie  Survival Time      */     public  static void  addcookie (Httpservletresponse response, string name,             String value,  int   MaxAge)  {       Cookie cookie =  new  
Cookies (Name, value);         if   (maxage > 0)    
        cookie.setmaxage (MaxAge);         //   Add to Client        
Response.addcookie (cookie); &NBSP;&NBSP;&NBSP;&NBSP}      /**      *   Remove all the & from the hard drivenbsp
Cookie      *      *   @param   request      *   @return      */     Www.2cto.com     public static  Map<String, Cookie>  Getallcookies (httpservletrequest request)  {       map<string,
 Cookie> cookie_map =  new  HashMap<String, Cookie> ();
       cookie[] cookies = request.getcookies ();         //  If there is  cookie,  deposited in  map          if  (cookies!= null ) {             for   ( int  i = 0; i <  cookies. length ; i++) &NBSp {              cookie_map.put (
Cookies.getname (),  cookies);
           }        }
        return  cookie_map; &NBSP;&NBSP;&NBSP;&NBSP}/**      *   passed  cookie in  Cookie    Name get  sessionid      *   @param   request  
    *   @param   name      *   @return      */     public static  String  Getsessionidbynameincookie (httpservletrequest request,string name) {     
  Map<String, Cookie> cookie_map=getAllCookies  (Request);         if  (Cookie_map.containskey (name)) {          
 cookie cookie = cookie_map.get (name);
            return  cookie.getvalue ();        }         return null
 ; &NBSP;&NBSP;&NBSP;&NBSP}}


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.