Using MongoDB and JSP to implement a simple shopping cart system Instance _jsp programming

Source: Internet
Author: User
Tags array length border color button type getmessage hash int size set set trim

This paper introduces the JSP programming technology to achieve a simple shopping cart program, specific as follows:

1 Problem description

Using JSP programming technology to achieve a simple shopping cart program, the specific requirements are as follows.

(1) using JSP to write a login page, the login information has a username and password, respectively, with two buttons to submit and reset the login information.

(2) write a JSP program to obtain the user submitted login information and query the database, if the user name is the name of the team members and the password for the corresponding number, the use of JSP built-in object to jump to the order page (show the type of goods in the store and price and other directory information) Otherwise, the JSP action prompts the user to login again (note: This page should include the previous login interface).

(3) When the customer fills in the quantity of the required goods and clicks the submit button, put the items ordered in the cart and display the relevant information in the cart, including the name and quantity of the goods and the total price of all the goods.

(4) The product information is written to the database, the price is calculated by looking for a database to complete.

The following features are selected:

(5) Implement a simple registration function, so that new users can write their own information (name and number) into the database, for later login to use

(6) Rewrite the related operation of the database into a JavaBean

2 Solutions

2.1 Implementation Features

(1) User login. (through query MongoDB database, complete login authentication)

(2) User registration. (Complete user registration by writing to MongoDB database)

(3) Remember the password. (By using cookies, remember the home page username and password function)

(4) View the goods. (by querying the MongoDB database, return the product specific information, and display in the Client interface)

(5) Purchase of goods.

(6) Shopping cart. (Show the user purchase specific information, delete the purchased goods or add the number of items purchased, calculate the total price of the user's current purchase of goods)

2.2 Final Operating effect chart

2.3 System function Frame Sketch

Figure I: A sample diagram of the system functional framework

Specific explanation:

(1) browser to open the homepage login.jsp user login page;

(2) Click to create a new user button to enter the REGISTER.JSP user registration page;

(3) Registration failure to stay in the register.jsp original page, registration success to jump to register_success.jsp registration success prompts the page, click the Back button, return to the landing page login.jsp pages;

(4) In the Homepage login.jsp page enters the user name and the password, requests sends to the LOGIN_ACTION.JSP Landing Processing script page, the data match succeeds jumps to the Welcome.jsp Shopping homepage page, otherwise jumps to the landing video login_fail.jsp page;

(5) After entering the Welcome.jsp Shopping homepage page, click on the next page and the previous button, you can view the current product information; the same item click Purchase button to achieve the purchase of a product, click many times to achieve the purchase of more than one item; Click to view Cart button, realize internal jump to cart.jsp shopping cart page, can produce see current purchase Commodity number, name, price, number of purchases, and total price information for all commodities, and provide the ability to delete purchased items and add the number of items purchased;

(6) Shopping home welcom.jsp page consists of header.jsp, main_shop.jsp, bottom.jsp three pages, as shown in Figure two below:

figure II: Shopping Home welcome.jsp page

2.4 About MongoDB Introduction and system environment configuration

MongoDB, a member of the NoSQL family, has abandoned complex relationships and associations between entities, compared to the commonly used relational databases (for example, MySQL, SQL Server, etc.). In other words, MongoDB is a document database, like our daily writing documents, do not have to worry about the specific content of various documents are not carefully sorted, can be stored in their own computer hard disk. Below please see a table of MongoDB and relational database noun concept tables:

relational database

Mongodb

Database (databases)

Database (databases)

Table (Tables)

Collection (collection)

Row (Row)

Document (Documents)

Column (columns)

Filed (Domain)

Index (indexed)

Index (indexed)

Table joins (table relationship)

No

Primary key (primary key)

Automatically set the _id field as the primary key

The table shows that in our familiar relational database, the concrete entity table corresponds to the collection in the MongoDB, the rows in the table correspond to the documents in the MongoDB collection, the columns in the table correspond to the fields in the MongoDB document, and the key primary keys are automatically generated in the MongoDB of the system. MONGODB Automatic generated primary keys are generated in a specific way, with 12 bytes, and 12 bytes generated as follows:

0|1|2|3 | 4|5|6 | 7|8 | 9|10|11

Time Stamp | Machine | PID | Counter

The above is the individual preliminary study MongoDB introduction, if has the mistake, welcome everybody circle friend correct.

Finished the concept, it is necessary to concrete use, MongoDB in and read the data format are Bson format, Bson format is a JSON-like format of data, its specific style as follows:

/* 7 CREATEDAT:2016/11/22 pm 3:52:51*/
{
  "_id": ObjectId ("5833f953e9d60125601a8c8b"),
  "Sid": "7",
  " Sname ":" Red rice Note4 ",
  " Sprice ":" 899 "
},/

* 8 createdat:2016/11/22 pm 3:53:19*/
{
  " _id ": ObjectId (" 5833f96fe9d60125601a8c8c "),
  " Sid ":" 8 ",
  " sname ":" Ordinary World ",
  " Sprice ":" The "
},/

* 9 Createdat : 2016/11/22 pm 3:53:43*/
{
  "_id": ObjectId ("5833f987e9d60125601a8c8d"),
  "Sid": "9",
  "sname": " Bucket continent ",
  " Sprice ":" 199 "
},

When we obtain the data from the MongoDB database query, the format is Bson format and cannot be directly matched with the data obtained by the client. Here, after I get the Bson format data in the database, I call the Bson.tomap () method in the MongoDB driver package, convert the Bson format to the map key value pair format string, and call the Map.get ("name") method in map to get the value of the specific key value pair To achieve a match with the data in the client page.

Finally, the key point is to import the MongoDB driver package into the new project to facilitate the client and business layer to manipulate the database. Here I am using the Mongo-java-driver-3.3.0.jar package, its version of the driver package download link: http://central.maven.org/maven2/org/mongodb/mongo-java-driver/

2.5 Core Functional Code explanation

(1) User login function

The

Implements user logins, mainly by code in the Login_action.jsp script, with specific comments in the code, as follows:

<%@ page language= "java" import= "java.util.*,com.mongodb.*" pageencoding= "UTF-8"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title>my JSP ' login_action.jsp ' starting page</title> <meta http-equiv= ' pragma ' cont Ent= "No-cache" > <meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" Co Ntent= "This are my page" > <!--<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >--> </he Ad> <body> <% response.setcontenttype ("Text/html;charset=utf-8"); Ensure that the displayed Chinese character information is displayed in the correct encoding Request.setcharacterencoDing ("Utf-8"); Ensure that the obtained Chinese character information obtains string username= (string) request.getparameter ("UserName") in the correct encoding method; Get login page Username string password= (string) request.getparameter ("PassWord");//Get login page password string checkBox = Request.getpar        Ameter ("Save_password"); Get the login page remember the Password Selection box property value Boolean login_test = false; Set Login Boolean value, if username and password match successfully, true try{//Connect to MongoDB service mongoclient mongoclient = new Mongoclient ("Local
       Host ", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("UserInfo");
      Gets the collection UserInfo System.out.println ("Collection UserInfo selected successfully") in the library database; dbcursor cursor = Coll.find (); 
      Query set userinfo Chinese document information int i=1; 
        while (Cursor.hasnext ()) {//Retrieve all the document information in the collection UserInfo System.out.println ("UserInfo document:" +i);       
        DBObject show = Cursor.next (); System.out.println (show); 
        @SuppressWarnings ("Rawtypes") Map Show1 = Show.tomap (); Converts the search result show (Bson type) to the map type String ToName = (string) show1.get ("username"); Extracts the property value String Topassword = (string) show1.get ("password") of the field name username in the map; Extract the property value of the field name PassWord in the map if (Toname.equals (userName) && topassword.equals (PassWord)) {//will be obtained from the database The username and password are validated against the data obtained in the form, and a successful match results in a login_test value of true System.out.println ("Login succeeded!!!!!
          "+" Username: "+toname+" Password: "+topassword);" 
          Request.getrequestdispatcher ("welcome.jsp"). Forward (request, response);
        Login_test = true;
        } System.out.println (Show1.get ("username"));
      i++;
     }}catch (Exception e) {System.err.println (E.getclass (). GetName () + ":" + e.getmessage ()); } if (login_test) {if ("Save". Equals (CheckBox)) {//cookie is encoded with Urlencoder.encode when accessed (PS: Urldecoder when read.) Decode) String name1 = Java.net.URLEncoder.encode (UserName, "UTF-8 ");
        Create two cookie object cookie Namecookie = new Cookie ("username", name1);
        
        Set the cookie to be valid for 3 days namecookie.setmaxage (60 * 60 * 24 * 3);
        String pwd = Java.net.URLEncoder.encode (PassWord, "UTF-8");
        Cookie Pwdcookie = new Cookie ("password", pwd);
        Pwdcookie.setmaxage (60 * 60 * 24 * 3);
        Response.addcookie (Namecookie);
       Response.addcookie (Pwdcookie); 
       }//Request.getrequestdispatcher ("welcome.jsp"). Forward (request, response);     
    Response.sendredirect ("welcome.jsp");   
       } else{Response.sendredirect ("login_fail.jsp");       
    Request.getrequestdispatcher ("loginfail.jsp"). Forward (request, response);

 }%> </body> </html>

(2) User Registration function

User registration functions to achieve the principle of basic and user login consistent, the only difference is that the user login is a query database, and user registration is written to the database, here is not to paste specific code, in the following specific coding to display.

(3) Remember the password function

The implementation remembers the password, here uses two cookies, when the user correctly logs on, Cookie_one obtains the user name, and adds to the current browser cookie, Cookie_two obtains the password, also adds to the current browser cookie. In the Login Home page username and password two input boxes to fill in the value of the system from the cookie to obtain the user name and password, so as to achieve the ability to remember the password. Specifically as follows:

 if (login_test) {if ("Save". Equals (CheckBox)) {//cookie for access Urlencoder.enco
        De to encode (PS: Urldecoder.decode for decoding when reading) String name1 = Java.net.URLEncoder.encode (UserName, "UTF-8");
        Create two cookie object cookie Namecookie = new Cookie ("username", name1);
        
        Set the cookie to be valid for 3 days namecookie.setmaxage (60 * 60 * 24 * 3);
        String pwd = Java.net.URLEncoder.encode (PassWord, "UTF-8");
        Cookie Pwdcookie = new Cookie ("password", pwd);
        Pwdcookie.setmaxage (60 * 60 * 24 * 3);
        Response.addcookie (Namecookie);
       Response.addcookie (Pwdcookie); 
       }//Request.getrequestdispatcher ("welcome.jsp"). Forward (request, response);     
    Response.sendredirect ("welcome.jsp");   
       } else{Response.sendredirect ("login_fail.jsp");       
    Request.getrequestdispatcher ("loginfail.jsp"). Forward (request, response); }

 

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;

String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
String username = "";
String password = "";

 Gets all cookies for the current site cookie[] cookies = request.getcookies (); for (int i = 0; i < cookies.length i++) {//iterate over the data in the cookie, find the user name, password data if ("username". Equals (cookies[i].ge Tname ()) {//Read Urldecoder.decode decoding (Ps:cookie access is encoded with Urlencoder.encode) Username = Java.net.URLDecoder.deco
     De (Cookies[i].getvalue (), "UTF-8"); else if ("Password". Equals (Cookies[i].getname ())) {password = Java.net.URLDecoder.decode (Cookies[i].getvalue (), "
     UTF-8 "); }}%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat
H%> "> <title> landing page </title> <meta http-equiv=" pragma "content=" No-cache ">  <meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "content-type" content= "text/" html Charset=utf-8 "> <meta http-equiv=" description "content=" This are my page "> <link rel=" stylesheet "type=" Text/css "href=" Css/login.css "> </head> <body> <div class=" Content "> <div class=" hea D "> <h1> simple Shopping cart </h1> </div> <!--login Panel--> <div class=" Panel "> <
        Form action= "login_action.jsp" method= "POST" > <!--account and password group--> <div class= "group" > <label> account </label> <input type= "text" placeholder= "Please enter account" Name= "username" value= "<%=username%" > "> </div> <div class=" group "> <label> password </label> <input type= "Password" placeholder=, please lose.Into the password "name=" password "value=" <%=password%> "> </div> <div> <input type=" checkbox " Value= "Save" name= "Save_password" > <label> Remember Password </label> </div> <div class= "gr
        OUP "> <label></label> </div> <!--login button--> <div class=" Login "> <button type= "Submit" Name= "Login" > Login </button> <button type= "reset" name= "reset" > Reset </b utton> </div> </form> </div> <!--registration button--> <div class= "register" &
      Gt <button onclick= "window.location.href= ' register.jsp '" > Create new Account </button> </div> </div> </bo

 Dy> </html>

(4) Inquiry goods and purchase goods

This function is mainly to operate the MongoDB database, return the specific information of the goods, as long as you understand the user login function, the function code here will soon be understood, the specific code behind the show.

(5) Shopping Cart

The function here is also the main operation of MONGODB data, through the user interaction with the client, the implementation of shopping cart-related functions, the specific code in the back of the show.

2.6 Specific coding

Specific coding of the explanation, according to the implementation of the general order to introduce the function, as follows:

2.6.1 User Login and remember password

First look is the login Homepage login.jsp page, in order to show beautiful, this object uses a Login.css file (the following pages are used Login.css file). Login.css specific code is as follows:

@CHARSET "UTF-8";

/* According to the sample requirements, add a light gray background * * * body{background-color: #F2F2F2;}


/* Set content module at the top of a distance 100px*/. Content {margin-top:80px} /* The overall style of the login and registration buttons * */. Content button {height:30px;/* login and registration button Height * * color:white;/* Login and register button font color is white/font-size:18px;/* login and  The font size of the registration button * * border:0px;/* No BORDER * * * * * padding:0px;/* no inner margin * * * cursor:pointer;/* Login and Registration button for hand shape * * * * * * * head name/ {text-align:center;/* Child content Center/}/* login panel/. Content. Panel {background-color:white;/* login panel background color is white */width:302px /* Width is 302px*/text-align:center;/* child content Center/margin:0px auto;/* itself Center/padding-top:10px;/* the top of the inner margin for 20px*/Padding-bot The inner margin at the bottom of the tom:10px;/* is 20px*/border:1px solid #ddd;/* Border color is gray/border-radius:5px;/* border Corner has 5px radians/* * Shopping homepage Shopping panel/. Con Tent. Panel1 {background-color:white;/* Shopping home panel background color is white */width:1000px;/* width is 600px*/text-align:center;/* child content Center * * M argin:0px auto;/* itself Center/border:1px solid #ddd;/* Border color is gray * * * border-radius:5px;/* Border Corner has 5px radians/}/* Login and Password Group * *. conten T. PAnel. Group {text-align:left;/* Child content Center/width:262px;/* width is 262px*/margin:0px Auto 20px;/* Center itself, and distance from the bottom with 20px spacing/}. C Ontent. Panel. Group Label {line-height:30px;/* height is 30px*/font-size:18px;/* font size is 18px*/}. Content. panel. Group Inpu t {display:block;/* is set to block, so that the input box is exclusive to one line */width:250px;/* width is 250px*/height:30px;/* height is 30px*/border:1px solid #ddd; /* The border of the input box * * * padding:0px 0px 0px 10px;/* left margin is 10px, looks beautiful * * * * font-size:16px;/* font size/}. Content. panel. Group Input:focus {border-left:1px solid #CC865E;/* When the input box becomes the focus, the left border color is programmed with brown/}. Content. panel. Login button {background-color: #CC865E;
  /* Button Background color */width:130px;/* button width/}. content. panel. Login Button:hover {background-color:white;/* button selected background color is white * * Color: #CC865E/* button is selected with brown/border:1px solid #CC865E;/* button selected, border color is brown/}/* Registration button. Content. Register {Text-alig n:center;/* the inner margin of the center/margin-top:20px;/* top is 20px*/} content. Register button {background-color: #466BAF;/* Button background color For Blue */width:180px;/* Pressbutton width/}. Content. Register Button:hover {background-color:white;/* button is selected, the background color is white/color: #466BAF; * The font color is blue when the/* button is selected *

 border:1px solid #466BAF;/* Button selected border color Blue/}

The

login.jsp specific code is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;

String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
String username = "";
String password = "";

 Gets all cookies for the current site cookie[] cookies = request.getcookies (); for (int i = 0; i < cookies.length i++) {//iterate over the data in the cookie, find the user name, password data if ("username". Equals (cookies[i].ge Tname ()) {//Read Urldecoder.decode decoding (Ps:cookie access is encoded with Urlencoder.encode) Username = Java.net.URLDecoder.deco
     De (Cookies[i].getvalue (), "UTF-8"); else if ("Password". Equals (Cookies[i].getname ())) {password = Java.net.URLDecoder.decode (Cookies[i].getvalue (), "
     UTF-8 "); }}%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat
H%> "> <title> landing page </title> <meta http-equiv=" pragma "content=" No-cache ">  <meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "content-type" content= "text/" html Charset=utf-8 "> <meta http-equiv=" description "content=" This are my page "> <link rel=" stylesheet "type=" Text/css "href=" Css/login.css "> </head> <body> <div class=" Content "> <div class=" hea D "> <h1> simple Shopping cart </h1> </div> <!--login Panel--> <div class=" Panel "> <
        Form action= "login_action.jsp" method= "POST" > <!--account and password group--> <div class= "group" > <label> account </label> <input type= "text" placeholder= "Please enter account" Name= "username" value= "<%=username%" > "> </div> <div class=" group "> <label> password </label> <input type= "Password" placeholder=, please lose.Into the password "name=" password "value=" <%=password%> "> </div> <div> <input type=" checkbox " Value= "Save" name= "Save_password" > <label> Remember Password </label> </div> <div class= "gr
        OUP "> <label></label> </div> <!--login button--> <div class=" Login "> <button type= "Submit" Name= "Login" > Login </button> <button type= "reset" name= "reset" > Reset </b utton> </div> </form> </div> <!--registration button--> <div class= "register" &
      Gt <button onclick= "window.location.href= ' register.jsp '" > Create new Account </button> </div> </div> </bo

 Dy> </html>

The

Logon processing script login_action.jsp code is as follows:

<%@ page language= "java" import= "java.util.*,com.mongodb.*" pageencoding= "UTF-8"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title>my JSP ' login_action.jsp ' starting page</title> <meta http-equiv= ' pragma ' cont Ent= "No-cache" > <meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" Co Ntent= "This are my page" > <!--<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >--> </he Ad> <body> <% response.setcontenttype ("Text/html;charset=utf-8"); Ensure that the displayed Chinese character information is displayed in the correct encoding Request.setcharacterencoDing ("Utf-8"); Ensure that the obtained Chinese character information obtains string username= (string) request.getparameter ("UserName") in the correct encoding method; Get login page Username string password= (string) request.getparameter ("PassWord");//Get login page password string checkBox = Request.getpar        Ameter ("Save_password"); Get the login page remember the Password Selection box property value Boolean login_test = false; Set Login Boolean value, if username and password match successfully, true try{//Connect to MongoDB service mongoclient mongoclient = new Mongoclient ("Local
       Host ", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("UserInfo");
      Gets the collection UserInfo System.out.println ("Collection UserInfo selected successfully") in the library database; dbcursor cursor = Coll.find (); 
      Query set userinfo Chinese document information int i=1; 
        while (Cursor.hasnext ()) {//Retrieve all the document information in the collection UserInfo System.out.println ("UserInfo document:" +i);       
        DBObject show = Cursor.next (); System.out.println (show); 
        @SuppressWarnings ("Rawtypes") Map Show1 = Show.tomap (); Converts the search result show (Bson type) to the map type String ToName = (string) show1.get ("username"); Extracts the property value String Topassword = (string) show1.get ("password") of the field name username in the map; Extract the property value of the field name PassWord in the map if (Toname.equals (userName) && topassword.equals (PassWord)) {//will be obtained from the database The username and password are validated against the data obtained in the form, and a successful match results in a login_test value of true System.out.println ("Login succeeded!!!!!
          "+" Username: "+toname+" Password: "+topassword);" 
          Request.getrequestdispatcher ("welcome.jsp"). Forward (request, response);
        Login_test = true;
        } System.out.println (Show1.get ("username"));
      i++;
     }}catch (Exception e) {System.err.println (E.getclass (). GetName () + ":" + e.getmessage ()); } if (login_test) {if ("Save". Equals (CheckBox)) {//cookie is encoded with Urlencoder.encode when accessed (PS: Urldecoder when read.) Decode) String name1 = Java.net.URLEncoder.encode (UserName, "UTF-8 ");
        Create two cookie object cookie Namecookie = new Cookie ("username", name1);
        
        Set the cookie to be valid for 3 days namecookie.setmaxage (60 * 60 * 24 * 3);
        String pwd = Java.net.URLEncoder.encode (PassWord, "UTF-8");
        Cookie Pwdcookie = new Cookie ("password", pwd);
        Pwdcookie.setmaxage (60 * 60 * 24 * 3);
        Response.addcookie (Namecookie);
       Response.addcookie (Pwdcookie); 
       }//Request.getrequestdispatcher ("welcome.jsp"). Forward (request, response);     
    Response.sendredirect ("welcome.jsp");   
       } else{Response.sendredirect ("login_fail.jsp");       
    Request.getrequestdispatcher ("loginfail.jsp"). Forward (request, response);

 }%> </body> </html>

The

Logon failure login_fail.jsp the page code as follows:

 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> landing failure </title> <meta http-equiv=" pragma "content=" No-cache "> <meta http- equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keyw Ords "content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <lin
  K rel= "stylesheet" type= "Text/css" href= "Css/login.css" > </head> <body> <div class= "Content" > <div class= "Panel1" > <h1> enter username and password incorrectly, please login again!!! </h1> </div> <div class= "register" > <button onclick= "window.location.href= ' login.jsp ' "> Back </button> </div> </div> </body> </html> 

2.6.2 User Registration

Register Home register.jsp page code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;       
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> registration page </title> <meta http-equiv=" pragma "content=" No-cache "> <meta http- equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keyw Ords "content=" Keyword1,keyword2,keyword3 "> <meta http-equiv=" content-type "content=" text/html; Charset=utf-8 "> <meta http-equiv=" description "content=" This are my page "> <link rel=" stylesheet "type=" Te Xt/css "href=" css/login.css > <script language= "JavaScript" > Function check () {var tmp,str       
        ; Str=document.myform.paSsword1.value;
        Tmp=document.myform.password2.value; if (str!= tmp) alert ("Two times password input is inconsistent, please confirm password!!!
      ");
      } </Script> </head> <body> <div class= "Content" > <div class= "Head" > <h1> Welcome to the simple shopping cart System registration page </h1> </div> <!--registration panel--> <div class= "Panel" > <f ORM name= "MyForm" action= "register_action.jsp" method= "POST" > <!--account and password group--> <div
      "Group" > <label></label> <input type= "text" placeholder= "Please enter the registration account" Name= "username1" > </div> <div class= "group" > <label></label> <input type= "password" pl Aceholder= "Please enter the registration password" name= "Password1" > </div> <div class= "group" > <label></lab
                   
      el> <input type= "password" placeholder= "Please confirm registration password" name= "Password2" > </div> <!--noteBook Button--> <div class= "Login" > <button type= "Submit" name= "register" onclick= "Check ()" > Registration </b
      utton> <button type= "reset" name= "Reset1" > Reset </button> </div> </form> 
      <div class= "Register" > <button onclick= "window.location.href= ' login.jsp '" > Return </button>

 </div> </div> </div> </body> </html>

The

Registration processing script register_action.jsp code is as follows;

<%@ page language= "java" import= "java.util.*,com.mongodb.*" pageencoding= "UTF-8"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
String Text_change = "Wait for registration"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title>my JSP ' register_action.jsp ' starting page</title> <meta http-equiv= ' pragma ' C Ontent= "No-cache" > <meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "Conten T-type "content=" Text/html;charset=utf-8 > <meta http-equiv= "description" content= "This are my page" > </hea D> <body> <% response.setcontenttype ("Text/html;charset=utf-8");
     Ensure that the displayed Chinese character information is displayed in the correct encoding modeRequest.setcharacterencoding ("Utf-8"); Ensure that the obtained Chinese character information obtains string username1= (string) request.getparameter ("username1") in the correct encoding method; Get page User name string password1= (String) request.getparameter ("Password1");/Get registration page password 1 String password2= (string) reques T.getparameter ("Password2")//Get the registration page Password 2 if (!password1.equals (PASSWORD2)) {//If the user entered the password is inconsistent two times, then jump to the original page of the Register register.jsp 
     , that is to achieve the Response.sendredirect effect ("register.jsp");
       try{//Connect to MongoDB service mongoclient mongoclient = new Mongoclient ("localhost", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("UserInfo");
      
       Gets the collection UserInfo System.out.println ("Collection UserInfo selected successfully") in the library database;
       DBObject user = new Basicdbobject (),//defines a Bson variable for storing registered username and password user.put ("username", userName1);      
User.put ("password", passWord1);       Coll.insert (user); Inserts the registered user information Response.sendredirect ("register_success.jsp") into the collection userinfo; After the registration succeeds, automatically jumps to the Registration Success prompt page}catch (Exception e) {System.err.println (). GetName (
     + ":" + e.getmessage ());

 }%> </body> </html>

Successful Registration Prompt page register_success.jsp page code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> registration Success </title> <meta http-equiv=" pragma "content=" No-cache "> <meta http- equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keyw Ords "content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <lin
  K rel= "stylesheet" type= "Text/css" href= "Css/login.css" > </head> <body> <div class= "Content" >
      <div class= "Panel1" > <h1> Congratulations, you have successfully registered a simple shopping cart system </h1> </div> <div class= "register" > <button onclick= "Window.location.href= ' login.jsp ' "> Back </button> </div> </div> </body> </html> 

2.6.3 View Products

First look at the shopping home welcome.jsp page code:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> Shopping page </title> <meta http-equiv=" pragma "content=" No-cache "> <meta http- equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keyw 
  Ords "content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <!-- <link rel= "stylesheet" type= "Text/css" href= "Styles.css" >--> </head> <frameset rows= "30%,60%,1" 0% "cols=" * "frameborder=" no "border=" 0 "framespacing=" 0 "> <frame src=" header.jsp "> <frame src=" Main_sho " p.jsp "> <frame src="Bottom.jsp" > </frameset> <body> </body> </html>

 

  Home Header header.jsp page code:

<%@ page language= "java" import= "java.util.*" contenttype= "text/html;charset=gb2312" pageencoding= "gb2312"%>
<% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title></title> <meta http-equiv=" pragma "content=" No-cache "> <meta http-equi v= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords "Content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <meta HT  tp-equiv= "Content-type" content= "text/html;charset=gb2312" > </head> <body topmargin= "0" leftmargin= "0" rightmargin= "0" style= "Background-color: #F2F2F2; Overflow-x:hidden;overflow-y:hidden" > <form actioN= "" "> <table width=" 100% "height=" "border=" 0 "cellpadding=" 0 "cellspacing=" 0 "align=center> <tr> <td bgcolor= "f9a859" valign= "Top" > <table width= "100%" height= "0" border= " align= "center" cellpadding= "0" cellspacing= "0" bgcolor= "#466BAF" > <tr> <td Alig n= "center" style= "Font-size:60px;color:white;" > Simple Shopping cart system </td> </tr> </table> </ td> </tr> <tr> <td bgcolor= "f9a859" valign= "Top" > <table width= "1 00% "height=" border= "0" align= "center" cellpadding= "0" cellspacing= "0" bgcolor= "#CC865E" > ;tr> <td align= "center" style= "Font-size:20px;color:white;" > welcome you to visit!</td> </tr> </table> </td&gt
       ;  </tr>     
       
       </table> </form> </body> </html> 

Tail bottom.jsp page code:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title>my JSP ' bottom.jsp ' starting page</title> <meta http-equiv=" Pragma "content=" n O-cache "> <meta http-equiv=" Cache-control "content=" No-cache "> <meta http-equiv=" Expires "content=" 0 " > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" Conte Nt= "This are my page" > </head> <body style= "Background-color: #F2F2F2; overflow-x:hidden;overflow-y: Hidden "> <hr> <h4 style=" Width:100%;text-align:center ">copyright @2016 dancing heart </h4> </BODY&G
T </html>

First center main_shop.jsp page code;

<%@ page contenttype= "TEXT/HTML;CHARSET=GBK" import= "Java.util.*,com.liuzhen.shop.mongodbbean"%> <% String
Path = Request.getcontextpath ();

String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
String Cp=request.getparameter ("CP");//CP to page//int page_number = Dbbean.gettotalpage ();
int currpage = Page_number; int currpage= (cp==null| |
cp== "")? 1:integer.parseint (CP);
string[][] ss = Mongodbbean.getgoodlist (Currpage);

int n = mongodbbean.getlength (ss); %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> Shopping page </title> <meta http-equiv=" pragma "content=" No-cache "> &L T;meta http-equiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http -equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" content= "This are my page" > <link rel= "stylesheet" type= "Text/css" href= "Css/login.css" > </head> <b Ody style= "Overflow-x:hidden;overflow-y:hidden" > <div class= "Content" > <div class= "Panel1" > <table Border= "1" align= "center" > <tr> <th width= "30%" align= "Center" > Item number </th> <th width= "30%" Ali gn= "Center" > Item name </th> <th width= "30%" align= "center" > Pricing </th> <th width= "50%" align= "center" &G Buy </th> </tr> <% for (int i=0;i<n;i++) {%> <tr> <td height= "30%" Ali gn= "center" ><%= ss[i][0]%></td> <td height= "30%" align= "center" ><%= Ss[i][1]%></td > <td height= "30%" align= "center" ><%= ss[i][2]%></td> <td "height=" 30% "center" >< A href= "buy.jsp?sid=<%= ss[i][0]%>&action=buy" > Purchase </a></td> </tr> <%}% > </table> <% int tp=mongodbbean.gettotalpage ();
  
  if (currpage!=1) {%> <a href= "main_shop.jsp?cp=<%=currpage-1%>" > previous page </a> <%} if (CURRPAGE!=TP) {%> <a href= "main_shop.jsp?cp=<%=currpage+1%>" > Next page </a> <%}%&gt  
  
  ; 
  <form action= "main_shop.jsp" name= "MyForm" > <select name= "cp" onchange= "Document.myform.submit ()" > <% for (int i=1;i<=tp;i++) {%> <option value= "<%=i%>" <%= (i==currpage)? " Selected ":" "%>> <%=i%> page </option> <%}%> </select> </form> </div> & Lt;div class= "Register" > <button onclick= "window.location.href= ' cart.jsp '" > View cart </button> </div

 > </div> </body> </html>

The

implements the ability to view goods, mainly by calling the Mongodbbean.java class, with the following specific code:

Package com.liuzhen.shop;
Import Java.util.Map;

Import Java.util.Vector;

Import com.mongodb.*;  public class Mongodbbean {static int span=5; Set JSP page table only page display item information row number is 5 line//Return all goods number in database SID public static string[] Getgood_sid () {string[] good_sid_temporary =  New STRING[100];
    Define a one-dimensional array of 100 for temporary storage of cargo numbers//Connect to MongoDB service mongoclient mongoclient = new Mongoclient ("localhost", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("good");
    Gets the collection good System.out.println ("Collection UserInfo selected successfully") in the library database; dbcursor cursor = Coll.find (); 
    Query Collection good Chinese document information int i=0;
         
      while (Cursor.hasnext ()) {//Retrieve all document information in the collection good DBObject show = Cursor.next (); @SuppressWarnings ("Rawtypes") Map Show1 = Show.tomap (); Converts the search result show (Bson type) to the map type String Tosid = (string) show1.get ("Sid"); Extract the field name Si in mapD's attribute value good_sid_temporary[i] = Tosid;
     Store the queried cargo number in the database into an array good_sid i++;  } string[] Good_sid = new String[i];
    To determine the final return array length for (int j=0;j<i;j++) {Good_sid[j] = Good_sid_temporary[j], based on the query data traversing the set Chinese file information I value;
  return good_sid; //Return all the names of the goods in the database sname public static string[] Getgood_sname () {string[] good_sname_temporary = new string[100];
    Defines a one-dimensional array of 100 for temporary storage of the cargo name/connection to the MongoDB service mongoclient mongoclient = new Mongoclient ("localhost", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("good");
    Gets the collection good System.out.println ("Collection UserInfo selected successfully") in the library database; dbcursor cursor = Coll.find (); 
    Query Collection good Chinese document information int i=0;        
      while (Cursor.hasnext ()) {//Retrieve all document information in the collection good DBObject show = Cursor.next (); @SuppressWarnings ("Rawtypes") Map Show1 = Show.tomap (); Converts the search result show (Bson type) to the map type String tosname = (string) show1.get ("sname");   Extract the attribute value of the field name sname in map good_sname_temporary[i] = tosname;
    Store the names of the goods queried in the database into an array good_sname i++;  } string[] Good_sname = new String[i];
    To determine the final return array length for (int j=0;j<i;j++) {Good_sname[j] = Good_sname_temporary[j], based on the query data traversing the set Chinese file information I value;
  return good_sname; //Return all goods prices in database Sprice public static string[] Getgood_sprice () {string[] good_sprice_temporary = new string[100 ];
    Defines a one-dimensional array of 100 of temporary storage prices for goods/connections to the MongoDB service mongoclient mongoclient = new Mongoclient ("localhost", 27017); There is no user name and password authentication method to login @SuppressWarnings ("deprecation") db db = Mongoclient.getdb ("library"); Connect to Database library Dbcollection coll = db.getcollection ("good");
    Gets the collection good System.out.println ("Collection UserInfo selected successfully") in the library database; dbcursor cursor = Coll.find ();
    
Query Collection good Chinese Document information    int i=0;        
      while (Cursor.hasnext ()) {//Retrieve all document information in the collection good DBObject show = Cursor.next (); @SuppressWarnings ("Rawtypes") Map Show1 = Show.tomap (); Converts the search result show (Bson type) to the map type String Tosprice = (string) show1.get ("Sprice");  Extract the attribute value of the field name sname in map good_sprice_temporary[i] = Tosprice;
    Stores the price of the goods queried in the array library into an array good_sprice i++;  } string[] Good_sprice = new String[i];
    To determine the final return array length for (int j=0;j<i;j++) {Good_sprice[j] = Good_sprice_temporary[j], based on the query data traversing the set Chinese file information I value;
  return good_sprice;  /////According to the current page number of pages, get the specific information of the current single page of goods from the database, and return specific information with two-dimensional data public static string[][] getgoodlist (int page) {string[][]
    Result=null; Vector<string[]> v=new vector<string[]> ();    Define a vector set, a record to store the specific information of a cargo string[] Good_sid = Getgood_sid ();  Get the cargo number string[] Good_sname = Getgood_sname (); Get the goods name string[] Good_sprice = Getgood_sprice (); Get the price of goods int len = Good_sid.length;  for (int i=0;i<span;i++) {int t = (page-1) *span+i;
      Get the cargo number if (T >= len) {//If the current cargo number is greater than the number already in the database, then break the loop;  } string[] Good_temp=new string[3];
      Defines a 3-length array for storing an item's number, name, price information good_temp[0]=good_sid[t];
      GOOD_TEMP[1]=GOOD_SNAME[T];
      GOOD_TEMP[2]=GOOD_SPRICE[T];   V.add (good_temp);
    The information of 1 items is deposited in the vector set} int size = V.size ();  Result=new string[size][]; According to the VERCOTR size, assign the number of rows to result to (int j=0;j<size;j++) {//return a value in the vector (which represents the SID, name, and price of an item) and assign it to result[j], i.e. 
    Result two-dimensional array one line represents an item specific information result[j]= (string[]) V.elementat (j);
  return result; ///According to the cargo SID, return its price information public static double GetPrice (String sid) {double = 0;//define the price of the returned item string[] G Ood_sprice = Getgood_sprice ();    Get the price of all items int i = integer.parseint (SID);    Converts a String type item number SID to an int string sprice = Good_sprice[i]; Price of the item according to SID = DOUBLE.PARsedouble (Sprice);
  Converts the price information of type string to a double and assigns a value to the. 
    (a) An array of length 2 returns the public static string[] Getdetail (String SID) {string[] Good_detail=null according to the cargo SID, returning the name and price of the goods;
    Good_detail = new String[2];   string[] Good_sname = Getgood_sname ();  Get all items name string[] Good_sprice = Getgood_sprice ();    Get all items price int i = integer.parseint (SID);    Converts a string item number SID to int good_detail[0] = good_sname[i];    According to the item number SID, the name is stored in the array good_detail good_detail[1] = good_sprice[i];
  According to the item number SID, get the item price to be stored in the array good_detail return good_detail;
    ///By querying the number of goods in the database, 5 acts a page, return the existing cargo pages public static int gettotalpage () {int page = 0;
    string[] Good_sid = Getgood_sid ();
    int len = good_sid.length;  page = len/span+ ((len%span==0)? 0:1);      
  A page of span (span value 5) behavior that calculates the number of Pages page return page with the goods;
  //Returns the number of rows for a two-dimensional array public static int GetLength (string[][] a) {return a.length; } public static VOID Main (String args[]) {//string[] Good_sid = Getgood_sid (); Define a one-dimensional array containing the cargo number//string[] Good_sname = Getgood_sname (); Define a one-dimensional array that holds the name of the goods//string[] Good_sprice = Getgood_sprice ();
Defines a one-dimensional array that holds the price of the goods///for (int j=0;j<10;j++) {//System.out.println ("Cargo sid:" +good_sid[j]);
System.out.println ("Goods sname:" +good_sname[j]);
SYSTEM.OUT.PRINTLN ("The Goods are Price:" +good_sprice[j]);
System.out.println ("**************************");
System.out.println ();
    } System.out.println ("Number of pagination (test):" +mongodbbean.gettotalpage ());
    String[][] Ss=mongodbbean.getgoodlist (Mongodbbean.gettotalpage ());
      for (int i=0;i<ss.length;i++) {System.out.println (ss[i][0]);
      System.out.println (ss[i][1]);
      System.out.println (ss[i][2]);
    System.out.println ("***********");
    int n = ss.length;
    
    
  SYSTEM.OUT.PRINTLN ("Array length is:" +n);

 }
  

}

2.6.4 Buy Goods

Implementation of the purchase of goods, through the BUY.JSP business Processing script call Shopcartbean.java class to implement.

The Shopcartbean.java class code is as follows:

Package com.liuzhen.shop;
Import Java.util.HashMap;
Import Java.util.Iterator;

Import Java.util.Set; public class Shopcartbean {//shopcartbean class Constructor public Shopcartbean () {}//define a key value pair that stores the integer values for ha
    Shmap hashmap<string, integer> hm=new hashmap<string, integer> ();
    
    Defines the total item price of the shopping cart, with the initial value of 0 double total=0; Add the purchased items into the hash table HM and calculate the total price after the successful purchase public void Add (String sid) {if (Hm.containskey (SID)) {//If HM
        that contains the key value pair SID, gets the value in the pair of the key value and adds 1 int xc= ((Integer) hm.get (SID)). Intvalue () +1;
      The XC value obtained above is deposited into HM Hm.put (Sid,new Integer (XC));      
      else {//If HM does not contain a key value pair SID, the key value pair is stored in HM and the key value pair value is 1 hm.put (sid,new Integer (1)); } total=total+mongodbbean.getprice (SID);
    After the purchase of goods, calculate the total price of goods}//Get the shopping cart current goods total price public double gettotal () {
///According to the item number SID, set the number of items purchased and store the purchase number in a hash table hm, and update the current shopping cart items Total price public void setcount (int c,string SID)    {int yc= ((Integer) hm.get (SID)). Intvalue ();
      total=total+ (C-YC) *mongodbbean.getprice (SID);  
    Hm.put (Sid,new Integer (c)); ///According to the item number SID, delete items from the shopping cart, and delete the number of items stored in the hash table HM, and the current shopping cart items Total price public void Deletefromcart (String sid) {int
      Yc= ((Integer) hm.get (SID)). Intvalue ();
      Total=total-yc*mongodbbean.getprice (SID);
    Hm.remove (SID);
    //Determine whether the current hash table HM is an empty public boolean isempty () {return hm.isempty (); 
      //Return the details of the user's purchase (item number, item name, item price, item purchase quantity) public string[][] Getcart () {//define a set set that holds the key name of the key value pair in the hash table HM
      Set<string> Ks=hm.keyset ();
      Defines an iterator that is used to traverse the set set iterator<string> ii=ks.iterator ();
      Gets the number of key-value pairs in the hash table HM int size=hm.size (); 
      Defines a two-dimensional array that stores information about the purchase of the item String rs[][]=new string[size][]; for (int i=0;i<size;i++) {string sid= (String) Ii.next ()///Key name for key value pairs, that is, number of goods Sid string[] SA  
        =new String[4];    Sa[0]=sid; Get Purchase goodsSid string[] Sat=mongodbbean.getdetail (SID);   Obtain the name and price of the goods purchased according to the SID of the goods sa[1]=sat[0];   Obtain the name of the purchase goods sa[2]=sat[1];  Get Price sa[3]= (Integer) hm.get (SID) for the purchase of goods. ToString ();    Obtain the quantity of goods purchased Rs[i]=sa;
    The single item is stored in the two-dimensional array RS in detail and then return RS;

 }

}

The

Buy.jps shopping processing script code is as follows:

<%@ page language= "java" import= "java.util.*" contenttype= "Text/html;charset=utf-8" pageencoding= "gb2312"%>
<% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <jsp:usebean id= "cart" scope= "session" class= "Com.liuzhen.shop.ShopCartBean"/> <% String action=
 Request.getparameter ("action"); 
   if (action==null) {%> <jsp:forward page= "main_shop.jsp"/> <%} else if (Action.trim (). Equals ("buy")) {
   String sid=request.getparameter ("Sid");  
 Cart.add (Sid.trim ()); %> <jsp:forward page= "main_shop.jsp"/> <%} else if (Action.trim (). Equals ("GC")) {String SID=REQUEST.G
   Etparameter ("Sid");
   String Count=request.getparameter ("Count");
 Cart.setcount (Integer.parseint (count), SID); %> <jsp:forward page= "cart.jsp"/> <%} else if (Action.trim (). Equals ("Del")) {String SID=REQUEST.G
   Etparameter ("Sid"); Cart.deleteFromcart (SID); %> <jsp:forward page= "cart.jsp"/> <%}%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title></title> <meta http-equiv=" pragma "content=" No-cache "> <meta http-equi v= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "keywords "Content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <!--&
Lt;link rel= "stylesheet" type= "Text/css" href= "Styles.css" >--> </head> <body> </body>

 </html>

2.6.5 Shopping Cart

Shopping cart function, mainly used cart.jsp page call Shopcartbean.java class to implement, Shopcartbean.java class code in the above has been given, below see cart.jsp Shopping cart page code:

<%@ page language= "java" import= "java.util.*" contenttype= "text/html;charset=gb2312" import= "
Com.liuzhen.shop.MongodbBean "pageencoding=" gb2312 "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <jsp:usebean id= "cart" scope= "session" class= "Com.liuzhen.shop.ShopCartBean"/> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > <html> <head> <base href= "<%=basepat H%> "> <title> shopping cart </title> <meta http-equiv=" pragma "content=" No-cache "> <meta http-e quiv= "Cache-control" content= "No-cache" > <meta http-equiv= "Expires" content= "0" > <meta http-equiv= "Keywo  RDS "Content=" Keyword1,keyword2,keyword3 > <meta http-equiv= "description" content= "This are my page" > <meta http-equiv= "Content-type" content= "text/html;charset=gb2312" > <link rel= "stylesheet" type= "Text/css""href=" Css/login.css "> </head> <body> <div class=" Content "> <div class=" Panel1 "> <% if (Cart.isempty ()) {%> <font color= "Red" size= "a" > Shopping cart is free of any merchandise!!! </Font> <%} else {%> <h2> shopping cart </h2> <table border= "1" > <tr> <td wi Dth= "27%" align= "Center" > Item number </td> <td width= "27%" align= "center" > Item name </td> <td width= "27%" a lign= "Center" > Pricing </td> <td width= "27%" align= "center" > Quantity </td> <td width= "27%" align= "Cente"
  R "> Buy </td> </tr> <% string[][] Ssa=cart.getcart (); for (int i=0;i<ssa.length;i++) {%> <tr> <td height= "30%" align= "center" ><%= Ssa[i][0]%>&l t;/td> <td height= "30%" align= "center" ><%= ssa[i][1]%></td> <td "height=" 30% "center" ><%= ssa[i][2]%></td> <td> <form action= "buy.jsp" method= "POST" &GT <input type= "Text" Name= "Count" value= "<%= ssa[i][3"%> "> <input type=" hidden "name=" Sid "Value=" <% 
   = Ssa[i][0]%> "> <input type=" hidden "name=" action "value=" GC "> </form> </td>    
 <td><a href= "buy.jsp?sid=<%= ssa[i][0]%>&action=del" > Delete </a></td> </tr> <%}%> </table> <br> <br> The total price of this order is: <%= Math.Round (Cart.gettotal () *100)/100.0%&
 Gt <%}%> <br> <div class= "register" > <button onclick= "window.location.href=" main_shop.

 JSP ' "> Continue shopping </button> </div> </div> </div> </body> </html>

Attach: Source Download: Source code

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.

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.