JSP training (14) -- shopping cart instance (top)

Source: Internet
Author: User

Objective: To learn how to store the information of a shopping cart and to learn how to implement common functions of a shopping cart. Main Content: l first analyzes the general process of online shopping by users; l introduces the data structure used to store shopping information; l compiles the shopping interface; l adds items to the shopping cart. 1. If you are interested in an item during browsing, you can view the information in the shopping cart at any time, if you do not want an item, you can delete it, modify the number of items, or clear the entire shopping cart. You can continue to select an item and add it to the shopping cart. Finally, the user can purchase these items and generate an order after entering the personal delivery address information and setting the transaction method. The website administrator can manage orders. This example simulates this process, but simplifies it: you can only select an item in the item list and add it to the shopping cart. After you confirm the purchase, you do not need to set the transaction method and payment. The actual processing process can be completed using the features described above. 2. Because the user can access the shopping cart information during the whole process of accessing the website, the shopping cart object should be stored in the session. Because the types and quantity of items purchased by users are not sure, we need to use a suitable data structure storage. We choose arraylist. Each item involves a quantity and needs to be encapsulated. The items and quantity are encapsulated into shopping items and items are used. Each item corresponds to one item and the quantity of such items. You need to write basic information about the item category. The reference code is as follows: 2.1 the item category contains two methods related to pagination. The dbbean used is described earlier. Package JavaBean; import Java. util. arraylist; import Java. SQL. *; public class goods {private string goodsid; private string goodsname; private float price; // item No. Public void setgoodsid (string goodsid) {This. goodsid = goodsid;} Public String getgoodsid () {return goodsid;} // item name public void setgoodsname (string goodsname) {This. goodsname = goodsname;} Public String getgoodsname () {return goo Dsname;} // item price public void setprice (float price) {This. price = price;} public float getprice () {return price;} public arraylist getgoodsbypage (INT pageno) {int number = 10; // number of records displayed on each page int begin = (pageno * Number)-9; int end = pageno * number; int Index = 1; dbbean DB = new dbbean (); // arraylist goods = new arraylist (); string SQL = "select * from goods"; resultset RS; try {r S = db.exe cutequery (SQL, null); While (RS. next () {// The record before in is not displayed if (index <begin) {index ++; continue ;} // The records after the end do not show if (index> end) break; index ++; string goodsid = Rs. getstring (1); string goodsname = Rs. getstring (2); float price = Rs. getfloat (3); goods G = new goods (); G. setgoodsid (goodsid); G. setgoodsname (goodsname); G. setprice (price); goods. add (g) ;}} catch (exception e) {e. prints Tacktrace ();} finally {dB. close () ;}return goods ;}public goods findgoodsbyid (string goodsid) {try {// write the SQL statement string SQL = "select * from goods where goodsid =? "; Dbbean DB = new dbbean (); arraylist Params = new arraylist (); Params. add (goodsid); resultset rs = db.exe cutequery (SQL, Params); If (RS. next () {// string goodsid = Rs. getstring (1); string goodsname = Rs. getstring (2); float price = Rs. getfloat (3); goods temp = new goods (); temp. setgoodsid (goodsid); temp. setgoodsname (goodsname); temp. setprice (price); dB. close (); Return temp;} else {return NULL;} c Atch (exception e) {system. out. println (E. tostring (); return NULL ;}} public int getpagecount () {try {// compile the SQL statement for querying database information string SQL = "select count (*) from goods "; dbbean DB = new dbbean (); resultset rs=db.exe cutequery (SQL, null); int number = 0; If (RS. next () number = Rs. getint (1); dB. close (); Return (number-1)/10 + 1;} catch (exception e) {return 0 ;}} 2.2 Item class package JavaBean; // shopping item Pu BLIC class item {private goods; private int quantity; Public item (goods D, int quantity) {This. goods = D; this. quantity = quantity;} public void setgoods (goods Goods) {This. goods = goods;} public goods getgoods () {return goods;} public void setquantity (INT quantity) {This. quantity = quantity;} public int getquantity () {return quantity;} 3. The item information display function adopts the MVC mode. For the view part, you do not need to enter the interface, you only need to display the information on the interface. Model section, which has been implemented in the previous code. In the controller section, you need to write getallgoods. java. The reference code is as follows: 3.1 interface code file name: goodslist. JSP <% @ page contenttype = "text/html; charset = gb2312" %> <% @ taglib prefix = "C" uri = "http://java.sun.com/jsp/jstl/core" %> <C: if test = "$ {pageno! = 1} "> <a href =" getallgoods? Pageno = 1 "> page 1 </a> <a href =" getallgoods? Pageno =$ {pageNo-1} "> previous page </a> </C: If> <C: If test =" $ {pageno! = Pagecounter} "> <a href =" getallgoods? Pageno =$ {pageno + 1} "> next page </a> <a href =" getallgoods? Pageno =$ {pagecounter} "> last page </a> </C: if> <br> <Table width = "200" border = "1" Height = "56"> <tbody> <tr> <TD> item No. </TD> <TD> item name </TD> <TD> item price </TD> </tr> <C: foreach Var = "G" items = "$ {goods}"> <tr> <TD >$ {G. goodsid} </TD> <TD >$ {G. goodsname} </TD> <TD >$ {G. price }</TD> <a href = "addtocart? Goodsid =$ {G. goodsid} "> Add to shopping cart </a> </TD> </tr> </C: foreach> </tbody> </table> 3.2 controller generation package servlet; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; import JavaBean. *; import Java. util. *; public class getallgoods extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {// response. setcontenttype ("text/html; c Harset = gb2312 "); // printwriter out = response. getwriter (); // Step 1: obtain user input string pageno = request. getparameter ("pageno"); int ipageno = 1; if (pageno! = NULL) {ipageno = integer. parseint (pageno);} // Step 2: Call JavaBean goods G = new goods (); arraylist goods = NULL; goods = G. getgoodsbypage (ipageno); int pagecount = G. getpagecount (); // out. println ("number of records:" + users. size (); // out. println ("Current page number:" + ipageno); // out. println ("total page number:" + pagecount); // Step 3: Pass the value request. setattribute ("goods", goods); Request. setattribute ("pageno", new INTEGER (ipageno); Request. setattribute ("Pagecounter", new INTEGER (pagecount); // Step 4: Select an interface to respond to the user string forward = "goodslist. JSP "; requestdispatcher RD = request. getrequestdispatcher (forward); Rd. forward (request, response);} public void dopost (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {doget (request, response );}} 4. display information in the shopping cart. This function directly retrieves information about the shopping cart from the session. Therefore, you only need to compile a JSP file that displays the information in the shopping cart without the need for controllers and models. The file name is Cart. JSP. The reference code is as follows: <% @ page contenttype = "text/html; charset = gb2312 "%> <% @ taglib prefix =" C "uri =" http://java.sun.com/jsp/jstl/core "%> information in the cart <br> <Table border = 1> <tr> <TD> item No. </TD> <TD> item name </TD> <TD> price </TD> <TD> quantity </TD> </tr> <C: foreach Var = "item" items = "$ {cart}"> <tr> <TD >$ {item. goods. goodsid} </TD> <TD >$ {item. goods. goodsname} </TD> <TD >$ {item. goods. price} </TD> <TD >$ {item. quantity} </TD> </C: foreach> </table> 5. add an item to the shopping cart in the MVC mode. First, consider input and output. The input for adding an item is the item information list interface. The output should be the added shopping cart information interface (you can also return to the item information interface ), you do not need to write these two interfaces. Considering the model, you need to write the shopping cart management Javabean to complete the processing. In the controller section, you need to obtain the selected item and add it to the management bean of the shopping cart to complete the addition. The following is the reference code. 5.1 model part file name cartmanager. javapackage JavaBean; import Java. util. arraylist; public class cartmanager {// indicates the shopping carprivate arraylist cart; Public void setcart (arraylist cart) {This. cart = cart;} public arraylist getcart () {return cart;} // Add item & quantity public arraylist addtocart (goods g, int quantity) {If (Cart = NULL) {// instantiate the cart object cart = new arraylist (); // Add it to the shopping cart item = new item (g, quantity); cart. add (I TEM);} else {// convert to array object items [] = cart. toarray (); Boolean find = false; // indicates whether the for (INT I = 0; I <items. length; I ++) {item temp = (item) items [I]; // determines whether the item to be added exists in the shopping cart if (temp. getgoods (). getgoodsid (). equals (G. getgoodsid () {temp. setquantity (temp. getquantity () + quantity); find = true; break ;}} if (! Find) {// Add to the shopping cart item = new item (g, quantity); cart. add (item) ;}} return cart ;}} 5.2 controller part file name: addtocart. javapackage servlet; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; import JavaBean. *; import Java. util. *; public class addtocart extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {// respo AUC. setcontenttype ("text/html; charset = gb2312"); // printwriter out = response. getwriter (); try {// get the ID of the item to be added string goodsid = request. getparameter ("goodsid"); // create the JavaBean object cartmanager = new cartmanager (); // obtain the session object httpsession session = request. getsession (true); // get the cart of the cart object arraylist cart = (arraylist) session. getattribute ("cart"); // use cart to initialize cartmanager. setcart (Cart ); // Construct the object goods G = new goods (); G = G. findgoodsbyid (goodsid); // out. println (G. getgoodsid (); cartmanager. addtocart (G, 1); // first save the shopping cart to the session. setattribute ("cart", cartmanager. getcart ();} catch (exception e) {// out. println (E. tostring ();} response. sendredirect ("cart. JSP ");} public void dopost (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {Doget (request, response) ;}} 6. The content of the servlet configuration web. xml file is as follows: <? XML version = "1.0" encoding = "UTF-8"?> <Web-app version = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet-Name> getallgoods </servlet-Name> <servlet-class> servlet. getallgoods </servlet-class> </servlet> <servlet-mapping> <servlet-Name> getallgoods </servlet-Name> <URL-pattern> /Getallgoods </url-pattern> </servlet-mapping> <servlet-Name> addtocart </servlet-Name> <servlet-class> servlet. addtocart </servlet-class> </servlet> <servlet-mapping> <servlet-Name> addtocart </servlet-Name> <URL-pattern>/addtocart </url-Pattern> </servlet-mapping> </Web-app> 7. Run and compile all files, then, access the getallgoods Servlet and select an item on the item information page to add it to the shopping cart. Then, you can see the information in the shopping cart.

 

Reference material: Basic tutorial on Java Web Programming

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.