Example of the Java session shopping Cart

Source: Internet
Author: User
Tags trim uuid java web

Session Shopping Cart Example one

The code is as follows Copy Code

Package cn.com.shopping;
Import java.io.IOException;
Import java.util.ArrayList;
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;
Complete purchase
public class Buyservlet extends HttpServlet {
Private static final long serialversionuid = 1L;
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
String id=request.getparameter ("id");
Book book= (book) Db.getall (). get (ID);
Plus the 剞 something bad behind program that closes the cookie session
Solution when blocking session
HttpSession session=request.getsession (FALSE);
A collection of all books that are saved by the user from the session (CART)
List list= (list) session.getattribute ("list");
if (list==null)
{
List=new ArrayList ();
Session.setattribute ("list", list);
}
List.add (book);
String Url=response.encoderedirecturl ("/session/sessioncountdemo");
Response.sendredirect (URL);
}
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Doget (Request,response);
}
}
Package cn.com.shopping;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.LinkedHashMap;
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;
Show book
public class Listbookservlet extends HttpServlet {
Private static final long serialversionuid = 1L;
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
HttpSession session=request.getsession ();
Out.print ("Our store is like the merchandise:<br/>");
map<string, Book > Map=db.getall ();
For (map.entry<string, book> entry:map.entrySet ())
{
Book Book=entry.getvalue ();
String Url=response.encodeurl ("/session/buyservlet?id=" +book.getid ());
Out.print (Book.getname () + "<a href= '" +url+ "' target= ' _blank ' > Buy </a><br/>");
}
}
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Doget (Request,response);
}
}
DB as a database
Class Db
{
private static map<string,book> map=new Linkedhashmap ();
Static
{
Map.put ("1", New book ("1", "Java Web Development", "WY", "Good Books"));
Map.put ("2", New book ("2", "Web Development", "ZT", "General"));
Map.put ("3", New book ("3", "Program Design", "DF", "Better Books"));
Map.put ("4", New book ("4", "Computer composition", "as", "General Good Books"));
Map.put ("5", New book ("5", "Principles of compilation", "Ty", "very Good books"));
Map.put ("6", New book ("6", "Network Maintenance", "HJ", "very Good books"));
}
public static Map GetAll ()
{
return map;
}
}
Book
Class Book
{
Private String ID;
private String name;
Private String author;
Private String description;
Public book () {
Super ();
TODO auto-generated Constructor stub
}
Public book (string ID, string name, string author, string description) {
Super ();
This.id = ID;
THIS.name = name;
This.author = author;
this.description = description;
}
Public String getId () {
return ID;
}
public void SetId (String id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getauthor () {
return author;
}
public void Setauthor (String author) {
This.author = author;
}
Public String getdescription () {
return description;
}
public void SetDescription (String description) {
this.description = description;
}
}
Package cn.com.shopping;
Import java.io.IOException;
Import Java.io.PrintWriter;
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;
public class Sessioncountdemo extends HttpServlet {
Private static final long serialversionuid = 1L;
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
HttpSession session=request.getsession ();
if (session==null)
{
Out.write ("You didn't buy any goods!") ");
Return
}
Out.write ("You have purchased the following goods:");
list<book> list= (list) session.getattribute ("list");
for (book Book:list)
{
Out.write (Book.getname ());
}
}
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Doget (Request,response);
}
}

The above is just a reference, the following detailed introduction to the Java Shopping cart some implementation methods

For information, find three ways to:

1. Use cookies to realize the shopping cart;

2. Implement the shopping cart with session;

3. Use cookies and database (shopping cart information persistence) to achieve 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:

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

The code is as follows Copy Code

Note:

1 conf.iduona_cashticket_cookie_startname = "iduona_cashticket_";

/**
* User Login
*
* @author Hongten
*/
public void Login () {
When the user log in, to read cookies, and the operation of persistent words, more login operation here omitted ....
Peristshoppingcartwhenuserlogin (NewUser);
}

/**
* Add Shopping cart <br>
* ============================================<br>
* User Login before:<br>
* When the user selects the cash coupon, click on the cash coupon to add to the cart, the information of the cash coupon (Cash coupon ID, purchase quantity) <br>
* Passed here, this time, backstage to do is to query from the cookie whether there is the same record, if the same record <br>
* Update the corresponding records; otherwise, add new records <br>
* User Login after:<br>
* After the user has logged in, if there are additional shopping cart operations, 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) {
Write ("Nullid");
else if (q = = NULL | | | q = = "") {
Purchase quantity, by default, below 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 is no cookie ...");
} else {
To determine whether a user is logged on
if (getuserinsession () = null) {
Boolean flag = true;
for (Cookie c:cookies) {
if (C.getname (). Equals (Conf.iduona_cashticket_cookie_startname + Cashticket.getid ())) {
Indicates that cookies are available in existing cookies and are updated.
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 with, read all cookies
Readshoppingcartfromcookie ();
// ==================================================

Write ("Success");
} else {
If the user logs in, the session exists with user, then the shopping cart information is persisted
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");
}
}
}
}
}
}

/**
* Read the shopping cart information from the cookie
*
* @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 is no cookie ...");
No cookies
} else {
for (Cookie c:cookies) {
SYSTEM.OUT.PRINTLN ("haha there are many cookies:" + c.getname () + "" + C.getvalue ());
}
}
}

   /**
     * Add cookie Operation
     *
  & nbsp;  * @param name
     *             Cookie's name
     * @param value
     *             the value of the cookie
     */
     public void Addcookie (string name, String value) {
        cookie cookie = n EW Cookie (Name.trim (), Value.trim ());
        cookie.setmaxage (2 * 60 * 60 * 1000);//set to 2 clock
   & nbsp;    servletactioncontext.getresponse (). Addcookie (cookie);
   }

/**
* Update Cookie operation
*
* @param c
* The cookie to be modified
* @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 the user is logged in, 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)) {
Get the name of the cookie: "Iduona_cashticket_45" and the value of the cookie: "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);
ShoppingCart shoppingcarttemp = new ShoppingCart ();
if (null!= temp) {
if (shoppingcartservice.isexistuserandcashticket (user, temp)) {
Perform an update operation
ShoppingCart Oldshoppingcart = shoppingcartservice.getbyuserandcashticket (user, temp);
Oldshoppingcart.setamount (amount);
Shoppingcartservice.update (Oldshoppingcart);
} else {
Otherwise save the 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 ();
}
}
}

/**
* Remove all cash coupons cookies operation
*/
public void Removeallcookies () {
Cookie cookies[] = Servletactioncontext.getrequest (). GetCookies ();
if (cookies = null | | Cookies.length < 0) {
No cookies
System.out.println ("There is no 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);
}
}
}
}

This is part of the code ....

Effect:

The situation inside the database:
Pre-logon data

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.