Hướng dẫn tạo giỏ hàng bằng session trong jsp servlet năm 2024

Sau đó bạn viết các lớp nối đến database phục vụ cho việc lấy dữ liệu. Có 2 lớp, lớp ConnectDBFactory dùng để kết nối đến database, ở đây chúng ta kết nối đến hệ quản trị cơ sở dữ liệu MySQL và lớp XulyDB bao gồm các thao tác xử lý căn bản.

package www.vvh.com.db; import java.sql.Connection; import java.sql.DriverManager; public class ConnectDBFactory { private static Connection con; public static Connection CreateMySqlConnection (String database)throws Exception{

String url="com.mysql.jdbc.Driver";  
Class.forName(url);  
String dbURL = "jdbc:mysql://localhost:3306/"   
  +database+"?user=root&password=";    
con=DriverManager.getConnection(dbURL);
return con;  
} }

package www.vvh.com.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class XulyDB { private Connection con; public XulyDB(){

try {  
  con=ConnectDBFactory.CreateMySqlConnection("qlsp");  
} catch (Exception e) {  
  e.printStackTrace();  
}  
} public SanPham getSanPham(String ms){
SanPham sp=null;
try {  
  Statement stmt=con.createStatement();  
  String sql="select * from sanpham where mssp='"+ms+"'";  
  ResultSet rs=stmt.executeQuery(sql);  
  if(rs.next()){  
    String mssp=rs.getString("mssp");  
    String ten=rs.getString("tenSP");  
    double dg=rs.getDouble("dongia");  
    sp=new SanPham(mssp,ten,dg);  
  }  
} catch (Exception e) {  
  e.printStackTrace();  
}  
return sp;  
} public ResultSet getAllProducts(){
ResultSet rs=null;  
try {  
  Statement stmt=con.createStatement();  
  String sql="select * from sanpham";  
  rs=stmt.executeQuery(sql);  
} catch (Exception e) {  
  e.printStackTrace();  
}  
return rs;  
} } Để cho việc kết nối thành công chúng ta cần phải copy driver của MySQL đến thư mục WEB-INF\lib.

Tiếp theo ta phải đặc tả 1 giỏ hàng để client có thể sử dụng. Ta nhận thấy rằng 1 giỏ hàng chứa nhiều món hàng, mỗi món hàng giữ thông tin về mã số của sản phẩm, số lượng đang có trong giỏ và đơn giá của mỗi sản phẩm. Đơn giá trong đối tượng này có thể không cần vì ta có thể dựa vào mã số sản phẩm có thể lấy được, tuy nhiên ở đây ý tôi muốn nói là bạn có thể lấy giá trong database làm giá cơ bản, bạn thêm vào các loại phí,… để tạo thành giá bán.

Code cho đối tượng món hàng như sau:

package www.vvh.com.spc; public class MonHang { private String msMH; private int soluong; private double dongia; public double getDongia() {

return dongia;  
} public void setDongia() { } public MonHang(String msMH, int soluong, double dongia) {
super();  
this.msMH = msMH;  
this.soluong = soluong;  
this.dongia = dongia;  
} public String getMsMH() {
return msMH;  
} public void setMsMH(String msMH) {
this.msMH = msMH;  
} public int getSoluong() {
return soluong;  
} public void setSoluong(int soluong) {
this.soluong = soluong;  
} public void setDongia(double dongia) {
this.dongia = dongia;  
} @Override public int hashCode() {
final int prime = 31;  
int result = 1;  
result = prime * result + ((msMH == null) ? 0 : msMH.hashCode());  
return result;  
} @Override public boolean equals(Object obj) {
if (this == obj)  
  return true;  
if (obj == null)  
  return false;  
if (getClass() != obj.getClass())  
  return false;  
MonHang other = (MonHang) obj;  
if (msMH == null) {  
  if (other.msMH != null)  
    return false;  
} else if (!msMH.equalsIgnoreCase(other.msMH))  
  return false;  
return true;  
} @Override public String toString() {
return msMH;  
} } Trong đối tượng giỏ hàng ta dùng 1 ArrayList để lưu trữ 1 danh sách các món hàng. Ở đây tôi chỉ viết 2 thao tác là thêm hàng vào giỏ và tính tổng giá tiền của giỏ hàng còn những phương thức khác như Xóa món hàng khỏi giỏ,… bạn có thể bổ sung thêm.

package www.vvh.com.spc; import java.util.ArrayList; public class Giohang { private ArrayListcart; public Giohang(){

cart=new ArrayList();  
} public void ThemHang(MonHang mh){
//Nếu món hàng đã có trong giỏ  
//thì cập nhập lại số lượng  
if(cart.contains(mh)){  
  MonHang hang=cart.get(cart.indexOf(mh));  
  hang.setSoluong(hang.getSoluong()+mh.getSoluong());  
}  
else{//còn không thì thêm mới  
  cart.add(mh);  
}  
} public double Tongtien(){
double tien=0;  
for(MonHang mh:cart){  
  tien+=mh.getDongia()*mh.getSoluong();  
}  
return tien;  
} public ArrayList getGH(){
return cart;  
} } OK, như vậy phần code xong rồi! Bạn tiến hành biên dịch và đóng gói nó lại.

Bạn tạo 1 file có tên build.bat với nội dung sau

javac -d . -encoding UTF-8 *.java

pause

Thực thi file này, đảm bảo bạn không nhìn thấy lỗi nào. Sau đó tiến hành đóng gói nó, bạn tạo file pack.bat có nội dung sau:

Bài trước mình có giới thiệu cho các bạn qua đối tượng HttpSeesion . Hôm nay mình làm thêm 1 demo về 1 giỏ hàng đơn giản thông qua đối tượng httpsession. Hy vọng bài viết giúp ích các bạn .

Cấu trúc thư mục 😦 Ở đây mình dùng Servlet 3.0 ) nên các bạn để ý . Mình sẻ dùng luôn thằng @webservlets (/duongdan). Nếu các bạn sử dụng phiên bản về trước thì phải mapping thằng servlet trong file web.xml (nếu ai thắc mắc thì có thề liên hệ mình rồi mình hướng dẫn).

Hướng dẫn tạo giỏ hàng bằng session trong jsp servlet năm 2024

Hình ảnh của ứng ụng :

Hướng dẫn tạo giỏ hàng bằng session trong jsp servlet năm 2024

Hướng dẫn tạo giỏ hàng bằng session trong jsp servlet năm 2024

Tạo đối tượng Book.java

package shopping; /

  • @author kobe
  • / public class Book { private String name; private double price; private int amount; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String name, double price, int soluong) { super(); this.name = name; this.price = price; this.amount = soluong; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return name + "-" + price + "-" + amount; } }
      
    Cart.java

package shopping; import java.util.ArrayList; /

  • @author kobe
  • */ public class Cart { private ArrayList cart; public Cart() { cart = new ArrayList(); } public void AddBook(Book book){ if(cart.contains(book)){ Book b = cart.get(cart.indexOf(book)); b.setAmount(b.getAmount()+book.getAmount()); }else{ cart.add(book); } } public Book GetBook(int i){ if(i<0 || i> cart.size()-1) return null; else return cart.get(i); } public boolean DelBook(String name){ Book book = new Book(name, 0d, 0); if(cart.contains(book)){ cart.remove(book); return true; } return false; } public int NumberOfBook(){ return cart.size(); } public double Total_Money(){ double money = 0d; for(Book bk : cart) money += (bk.getPrice()*bk.getAmount()); return money; } }

Servlet Shop.java

package shopping; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /

  • @author kobe
  • Servlet implementation class Shop / @WebServlet("/shop") public class Shop extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /*
  • @see HttpServlet

    doPost(HttpServletRequest request, HttpServletResponse response)

    */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); double total = 0d; synchronized (session) { out.println(""); out.println("Shop Book"); out.println("

    fdf5e6\">");

    out.println("

    Welcome to Shop Book

    "); out.println("
    "+ "

    Select Book : "+ ""+ "Amount : "+ " "+ "

    Infomation of Your Cart

    "+ ""+ ""+ ""+ ""+ ""+ ""+ ""+ ""); Cart cart = (Cart) session.getAttribute("cart"); if(cart==null) cart = new Cart(); total = cart.Total_Money(); int order; for(int i = 0;i"+ ""+ ""+ ""+ ""+ ""+ ""); } out.println("
    OrderProductAmoutPriceTotal
    "+ ++order +""+bk.getName()+""+bk.getAmount()+""+bk.getPrice()+""+bk.getAmount()*bk.getPrice()+"
    "+ "

    Total : " + total +"$

    "); out.println("
    "); out.println(""); out.println(""); } } }

Servlet Process

package shopping; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /

  • Servlet implementation class Process / @WebServlet("/process") public class Process extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /*
  • @see HttpServlet

    doPost(HttpServletRequest request, HttpServletResponse response)

    */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession seesion = request.getSession(); synchronized (seesion) { Cart cart = (Cart) seesion.getAttribute("cart"); if(cart == null) cart = new Cart(); String book = request.getParameter("cboBook"); String amout = request.getParameter("tfAmout"); int am = Integer.parseInt(amout); if(am>0){ double price = checkPrice(book); Book bk = new Book(book, price, am); cart.AddBook(bk); seesion.setAttribute("cart", cart); } } RequestDispatcher dispatcher = request.getRequestDispatcher("/shop"); dispatcher.forward(request, response); } private double checkPrice(String str){ switch (str) { case "Ajax":return 10000d; case "PHP":return 15000d; case "Java":return 20000d; case "C#":return 14000d; case "JSP":return 25000d; } return 0; } }