Artikel ini membagikan kode spesifik dari kasus keranjang belanja Javaweb untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
1. Struktur Direktori Proyek
2. Kode Sumber
Paket-Lapisan Dao : bookdao.java
Paket com.dao; import java.util.map; import com.db.db; import com.domain.book; kelas publik bookdao {peta publik getAll () {return db.getall (); } Buku publik Find (string id) {return (book) db.getall (). get (id); }}Paket DB: DB.java - Database Simulasi
Paket com.db; import java.util.linkedhashmap; import java.util.map; import com.domain.book; import com.sun.org.apache.bcel.internal.generic.new; // mewakili database // mewakili database public class db {private static Map = New LinkHas; static {map.put ("1", buku baru ("1", "Javaweb Development", "Lao Zhang", 38, "A Good Book")); map.put("2","new Book("2","jdbc development","Lao Li",18,"a good book")); map.put("3", new Book("3","ajax development","Lao Tong",328,"a good book")); map.put("4", new Book("4","jbpm development","Lao Bi",58,"a good buku ")); peta.put (" 5 ", buku baru (" 5 "," Struts Development "," Lao Fang ", 28," A Good Book ")); peta.put (" 6 ", buku baru (" 6 "," pengembangan musim semi "," Lao Fang ", 98," A Good Book "));} peta static publik getall () {) {{A Good Book"));Paket Domain:
Book.java: Kelas Entitas Buku
Paket com.domain; // kelas entitas buku kelas publik {private string id; nama string pribadi; penulis string pribadi; harga ganda pribadi; deskripsi string pribadi; buku publik () {super (); // TODO Stub Konstruktor yang Dihasilkan Otomatis} Buku Publik (ID String, Nama String, Penulis String, Harga Ganda, Deskripsi String) {Super (); this.id = id; this.name = name; this.author = penulis; this.price = harga; this.description = description; } public String getId () {return id; } public void setId (string id) {this.id = id; } public string getName () {return name; } public void setName (name string) {this.name = name; } public String getAuthor () {return author; } public void setauthor (string worhor) {this.author = penulis; } public double getPrice () {harga kembali; } public void setPrice (harga ganda) {this.price = harga; } public String getDescription () {return description; } public void setDescription (deskripsi string) {this.description = description; }}Cart.java: Kelas Keranjang Belanja
Paket com.domain; import java.util.linkedhashmap; import java.util.map; // keranjang belanja yang mewakili pengguna // keranjang belanja yang mewakili keranjang kelas publik pengguna {peta pribadi <string, cartitem> peta = new LinkedHashMap (); harga ganda pribadi; // Ingat berapa banyak semua item dalam biaya keranjang belanja void public add (buku buku) {// lihat apakah ada di keranjang belanja, dan item belanja yang sesuai dengan buku yang akan ditambahkan item cartitem = map.get (book.getid ()); if (item == null) {item = cartitem baru (); item.setbook (buku); item.setquantity (1); peta.put (book.getId (), item); } else {item.setQuantity (item.getQuantity ()+1); }} peta publik <string, cartitem> getMap () {return map; } public void setMap (peta <string, cartitem> peta) {this.map = peta; } public double getPrice () {ganda totalPrice = 0; untuk (map.entry <string, cartitem> entri: map.entryset ()) {cartitem item = entry.getValue (); TotalPrice += item.getPrice (); } this.price = TotalPrice; harga kembali; } public void setPrice (harga ganda) {this.price = harga; }}Cartitem.java: Item belanja
paket com.domain; // digunakan untuk mewakili produk tertentu dan berapa kali muncul (item belanja) cartitem kelas publik {buku buku pribadi; kuantitas int pribadi; harga ganda pribadi; buku publik getBook () {Buku kembali; } public void setbook (buku buku) {this.book = book; } public int getquantity () {kuantitas pengembalian; } public void setquantity (int kuantitas) {this.quantity = kuantitas; this.price = this.book.getPrice () * this.quantity; } public double getPrice () {harga kembali; } public void setPrice (harga ganda) {this.price = harga; }}Paket Layanan: Lapisan Layanan
Businessservice.java:
package com.service;import java.util.Map;import com.dao.BookDao;import com.domain.Book;import com.domain.Cart;import com.domain.CartItem;//Business class, provide all services to the web layer in a unified manner public class BusinessService { private BookDao dao = new BookDao(); peta publik getAllBook () {return dao.getall (); } Buku Publik FindBook (ID String) {return dao.find (id); } // Hapus item belanja di keranjang belanja public void deleteCartitem (ID string, cart cart) {cart.getMap (). Hapus (id); } // Bersihkan keranjang belanja public void clearcart (cart cart) {cart.getMap (). Clear (); } // Ubah jumlah item belanja void public voideiteMquantity (ID string, kuantitas string, keranjang keranjang) {item cartitem = cart.getMap (). Get (id); item.setquantity (integer.parseint (kuantitas)); }}Lapisan web:
ListBookServlet.java: Tampilkan semua buku
Paket com.web.controller; import java.io.ioException; impor java.io.printwriter; import java.util.map; impor javax.servlet.servletException; import javax.servlet.http.httpservlet; impor javax.servlet.htp.htp.htpservlet; impor javax.servlet.htp.htpetpetpetveT; javax.servlet.http.HttpServletResponse;import com.service.BusinessService;//Get all books//Get all books public class ListBookServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BusinessService service = new Businessservice (); Peta peta = service.getAllBook (); request.setAttribute ("peta", peta); request.getRequestDispatcher ("/web-inf/jsp/listbook.jsp"). Forward (Request, Response); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}Buyservlet.java: memproses permintaan pembelian
Paket com.web.controller; impor java.io.ioException; impor javax.servlet.servletException; impor javax.servlet.http.httpservlet; import javax.servlet.htp.htpservletrequest; impor javax.servlet.htp.htpservletRequest; impor javax.servlet.htppepprepcrepcrepprepcrepcrepprepcrepon; com.domain.cart; impor com.service.businessservice; // lengkap pembelian buku // lengkap pembelian buku pembelian kelas publik Buyservlet memperluas httpservlet {public void doGet (httpservletRequest request, httpservletResponse) DoMPLOPLEMETETE (IdePparETETETE (IdePparETEE (IDEPPARETE (IDEPPEETE (IDEPPEETE (IDEPPEETE (IDEPPEETE (IDEPPEETE (IDEP (IDEPPEETE (IDEPPEETSEPONE ( Layanan Layanan Bisnis = BusinessService baru (); Buku buku = service.findbook (id); // Dapatkan keranjang keranjang belanja pengguna = (cart) request.getSession (). GetAttribute ("cart"); if (cart == null) {cart = cart baru (); request.getSession (). setAttribute ("cart", cart); } // Tambahkan buku ke keranjang belanja pengguna dan lengkapi pembelian cart.add (buku); //response.sendredirect("/web-inf/jsp/listcart.jsp "); request.getRequestDispatcher ("/web-inf/jsp/listcart.jsp"). Forward (Request, Response); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}DeleteItemservlet.java: hapus produk tertentu
Paket com.web.controller; import java.io.ioException; import javax.servlet.servletException; import javax.servlet.http.httpservlet; import javax.servlet.htp.htpservletrequest; impor javax.servlet com.domain.cart; impor com.service.businessservice; // hapus item belanja yang ditentukan kelas publik deleteItemServlet memperluas httpservlet {public void doGet (httpservletRequest, httpservletResponse response) dontan (IdePetException, ioException {httpserVletResponse. Cart cart = (cart) request.getSession (). GetAttribute ("cart"); Layanan Layanan Bisnis = BusinessService baru (); service.deleteCartitem (id, cart); // hapus dengan sukses request.getRequestDispatcher ("/web-inf/jsp/listcart.jsp"). Forward (Request, Response); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}Clearcartservlet.java: Hapus gerobaknya
Paket com.web.controller; import java.io.ioException; impor java.io.printwriter; import javax.servlet.servletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservlet; javax.servlet.http.httpservletResponse; import com.domain.cart; impor com.service.businessservice; // hapus clearcartservlet kelas publik, carttpservlet {cartsceptexcepteon (httpservletequest permintaan, httpsceptexcepteon (httpservletequest, httpservet {htponceptexcepteon (httpservletequest permintaan, httpservlet {htponcceptexcepteon (httpservleteDrequest, httpservet {htponceppepsceptexceptexcepteon (httpservleteDrequest, httpservet {htponceppepsceptexceptexcepteon) (Cart) request.getSession (). GetAttribute ("cart"); Layanan Layanan Bisnis = BusinessService baru (); service.clearcart (cart); request.getRequestDispatcher ("/web-inf/jsp/listcart.jsp"). Forward (Request, Response); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}Changequantityservlet.java: Modifikasi jumlah produk yang ditentukan dalam keranjang belanja
Paket com.web.controller; import java.io.ioException; impor java.io.printwriter; import javax.servlet.servletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservlet; javax.servlet.http.httpservletResponse; import com.domain.cart; import com.service.businessservice; // ubah buku dalam keranjang belanja ke kuantitas public -lomplayservlet yang ditentukan httpservlet {public void doget (httpservlet httpservlet {public void doget (httpservlet httpservlets httpservlet {public void doget (httpservlets httpservlets httpservlet {public void doget (httpservlets httpservlet ServletException, ioException {string id = request.getParameter ("id"); Kuantitas string = request.getParameter ("kuantitas"); Cart cart = (cart) request.getSession (). GetAttribute ("cart"); Layanan Layanan Bisnis = BusinessService baru (); service.changeitemquantity (id, kuantitas, kereta); request.getRequestDispatcher ("/web-inf/jsp/listcart.jsp"). Forward (Request, Response); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {doGet (permintaan, respons); }}JSP Halaman:
Webroot/web-inf/jsp/listbook.jsp: Tampilkan daftar buku
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Book List Page</title> </head> <body style="text-align: center"> <h1>Book List</h1> <table> <ttr> <td>Book Title</td> <td>Author</td> <td>Selling Price</td> <td>Description</td> <td>Operation</td> </tr> <C: foreach var = "entri" item = "$ {MAP}"> <tr> <td> $ {entry.value.name} </td> <td> $ {entry.value.Author} </td> <td> $ {entry.value.price} </td> <dd> $ {entry.value.price} </td> <dd> $ {entry.value.price} </td> <dd> $ {entry.value.price} </td> <dd> $ {entry.value.price} </td> <dd> $ {entry. <a href = "$ {pageContext.Request.contextPath}/servlet/buyservlet? id = $ {entry.value.id}" rel = "nofollow eksternal" target = "_ blank"> Beli </a> </td> </tru- </c: foreach> </tabel> </a> </td> </tru> </c: foreach> </tabel>Webroot/web-inf/jsp/listcart.jsp: Tampilkan daftar keranjang belanja
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transisi // en "> <html> <head> <title> daftar mobil </iteme> <script type =" text/javascript "> function deleteItem (id) {var b = window.confirm (" Apakah Anda mengkonfirmasi hapus ?? "); if (b) {window.location.href = "$ {pagecontext.Request.contextPath}/servlet/deleteItemservlet? id =" rel = "nofollow eksternal" +id; }} function clearcart () {var b = window.confirm ("Apakah Anda mengkonfirmasi pembersihan ??"); if (b) {window.location.href = "$ {pagecontext.Request.contextPath}/servlet/clearcartservlet" rel = "nofollow eksternal"; }} function changeFquantity (input, id, oldValue) {var kuantitas = input.value; // Dapatkan nomor yang akan dimodifikasi SDFSFS /* // Periksa apakah jumlah input pengguna adalah angka jika (isnan (kuantitas)) {waspada ("Harap masukkan nomor !!"); input.value = oldValue; kembali; } */// Periksa apakah jumlah input pengguna adalah bilangan bulat positif if (kuantitas <0 || kuantitas! = ParseInt (kuantitas)) {peringatan ("Harap masukkan bilangan bulat positif !!"); input.value = oldValue; kembali; } var b = window.confirm ("Anda mengonfirmasi bahwa jumlah buku dimodifikasi menjadi:" + kuantitas); if (b) {window.location.href = "$ {pageContext.Request.contextPath}/servlet/changequantityservlet? id =" rel = "nofollow eksternal" + id + "& kuantitas =" + kuantitas; }} </script> </head> <body style = "text-align: center"> <h1> Daftar keranjang belanja </h1> <c: if test = "$ {kosong (cart.map)}"> Anda tidak membeli item apa pun! Lai Lai </c:if> <c:if test="${!empty(cart.map)}"> <table> <tr> <td> <td>Book Title</td> <td>Author</td> <td>Unit Price</td> <td>Quantity</td> <td>Subtotal</td> <td>Operation</td> </td> <c:forEach var = "entri" item = "$ {cart.map}"> <tr> <td> $ {entry.value.book.name} </td> <td> $ {entry.value.book.Author} </td> <td> <"TEPPS ENTHER.VALUE.Book.PRICH} </td> <" TD = "TEPPET =" value = "$ {entry.value.quantity}" onchange = "changequantity (this, $ {entry.key}, $ {entry.value.quantity})"> </td> <td> $ {entry.value.price} </td> <td> <td> "javin" (a oval "</td </td> <td> <td> <td oval" </td (td> </td "</td" </td (td " rel = "eksternal nofollow" onclick = "deleteItem ($ {entry.key})"> hapus </a> <!-Hapus perilaku default hyperlink-> </td> </pr> </c: foreach> <ttr> <td colspan = "3"> Total harga </td> <ttr> <td colspan = "3"> Total harga </t td> <ttr> <td colspan = "3"> </td colspan = "2"> </td colspan = "2"> </td colspan = "TD colspan =" <td colspan = "1"> <a href = "javaScript: void (0)" rel = "eksternal nofollow" rel = "eksternal nofollow" onclick = "clearcart ()"> Bersihkan keranjang </a> </td> </tr> </table> </c: if> </body> </htm>Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.