Giỏ hàng với Struts và Netbeans
Trong bài này tôi hướng dẫn các bạn làm 1 giỏ hàng đơn giản với struts. Ví dụ này đã được thực hiện với jsp chuẩn tại bài Giỏ hàng đơn giản với JSP. Các bạn tham khảo lại bài này.
Cấu trúc của chương trình sau khi hoàn thành của project:

1>Database
Bạn xem lại bài viết tôi đã đề cập ở phần trên để thiết lập database
2> Project
Trong Netbeans bạn tạo 1 Web Project mới có tên ShoppingCartWithStruts. Nhớ chọn FrameWork là Struts như hình

Thêm 1 ActionForm bằng cách nhấn phải chuột lên Source package chọn như hình:

Cửa sổ xuất hiện:

Sửa code lại như sau:
| package vovanhai.wordpress.com;import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors; public class ItemActionForm extends org.apache.struts.action.ActionForm { private String mssp; public double getDongia() { public void setDongia(double dongia) { public String getMssp() { public void setMssp(String mssp) { public int getSoluong() { public void setSoluong(int soluong) { /** /** |
Tiếp theo bạn cần phải viết các class nối CSDL, xử lý giỏ hàng như trong bài trước đã đề cập. Code của chúng như sau:
Lớp ConnectDBFactory.java
| package vovanhai.wordpress.com.db;import java.sql.Connection; import java.sql.DriverManager; public class ConnectDBFactory { public static Connection CreateMySqlConnection return con; |
Lớp SanPham.java
| package vovanhai.wordpress.com.db;public class SanPham { private String msSP; private String tenSP; private double dongia; public SanPham() { @Override |
Lớp XulyDB.java
| package vovanhai.wordpress.com.db;import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class XulyDB { public XulyDB(){ public SanPham getSanPham(String ms){ try { public ResultSet getAllProducts(){ |
Lớp MonHang.java
| package vovanhai.wordpress.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.equals(other.msMH)) return false; return true; } @Override public String toString() { return msMH; } } |
Lớp GioHang.java
| package vovanhai.wordpress.com.spc;import java.util.ArrayList;
public class Giohang { public Giohang(){ public void ThemHang(MonHang mh){ public double Tongtien(){ public ArrayList<MonHang> getGH(){ |
Tiếp theo bạn phải thêm Struts Action như hình sau


Code của lớp này
| package vovanhai.wordpress.com;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForward; import vovanhai.wordpress.com.db.XulyDB; import vovanhai.wordpress.com.spc.Giohang; import vovanhai.wordpress.com.spc.MonHang; public class ShoppingAction extends org.apache.struts.action.Action {
/* forward name=”success” path=”" */ private final static String SUCCESS = “success”; private final static String INVOICE = “hoadon”;
/** * This is the action called from the Struts framework. * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * @throws java.lang.Exception * @return */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //Nhấn nút mua hàng if(request.getParameter(“mua”)!=null){ //Lấy dữ liệu nhập từ ngưới dùng ItemActionForm frm=(ItemActionForm)form; HttpSession session =request.getSession(); //Lấy giỏ hàng Giohang cart=(Giohang)session.getAttribute(“giohang”); if(cart==null)//nếu chưa có giỏ hàng cart=new Giohang();//thì thêm mới //Lấy giá của sản phẩm XulyDB db=new XulyDB(); double dongia=db.getSanPham(frm.getMssp()).getDongia(); //Thêm hàng vào giỏ cart.ThemHang(new MonHang(frm.getMssp(), frm.getSoluong(),dongia )); //lưu lại giỏ hàng session.setAttribute(“giohang”, cart); } //Nhấn nút In hóa đơn else if(request.getParameter(“hd”)!=null){ return mapping.findForward(INVOICE); } return mapping.findForward(SUCCESS); } } |
Cấu hình struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts-config PUBLIC“-//Apache Software Foundation//DTD Struts Configuration 1.2//EN” “http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd”> <struts-config> <message-resources parameter=”com/myapp/struts/ApplicationResource”/> </struts-config> |
3> Viết các trang JSP
Trang shopping.jsp
| <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”><%@page import=”java.sql.ResultSet”%> <%@page import=”java.util.ArrayList”%> <%@page import=”vovanhai.wordpress.com.db.*”%> <%@page import=”vovanhai.wordpress.com.spc.*”%> <%@taglib prefix=”html” uri=”http://struts.apache.org/tags-html” %> <head> ResultSet rs = db.getAllProducts(); <hr/> %> |
Trang hoadon.jsp
| <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”><%@page import=”java.util.ArrayList”%> <%@page import=”vovanhai.wordpress.com.db.*”%> <%@page import=”vovanhai.wordpress.com.spc.*”%> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″> <title>Hóa đơn</title> </head> <body> <h1 align=”center”>HÓA ĐƠN BÁN HÀNG</h1> <table border=”1″ width=”100%”> <tr><th>MSSP</th> <th>Tên sản Phẩm</th> <th>Số lượng</th> <th>Đơn giá</th></tr> <% Giohang cart=(Giohang)session.getAttribute(“giohang”); java.text.NumberFormat fmt = java.text.DecimalFormat.getInstance(); if(cart!=null){ XulyDB db=new XulyDB(); ArrayList<MonHang> ds=cart.getGH(); for(MonHang mh:ds){ SanPham sp=db.getSanPham(mh.getMsMH()); %> <tr> <td><%= mh.getMsMH()%></td> <td><%= sp.getTenSP()%></td> <td><%= mh.getSoluong()%></td> <td><%=fmt.format(mh.getDongia())%></td> </tr> <% } %> </table> <h2 align=”right”>Tổng tiền:<%=fmt.format(cart.Tongtien()) %></h2> <%} %> <hr/> Nhấn vào <a href=”shopping.jsp”>đây để</a> quay lại trang mua hàng </body> </html> |
Kết quả thực thi:


Chúc thành công!
Thức said
Thầy ơi, em làm theo bài của thầy nhưng sao khi em add cùng một món hàng mà giỏ hàng kô tăng số lượng mà lại tăng thêm một dòng. Thầy giúp em với.
Thức said
Sau khi Debug thì em đã tìm ra lỗi là nằm ở hàm add trong class giohang rồi thưa thầy. Hàm add em viết giống thầy nhưng nó chỉ chạy phần add new chứ kô chạy phần check xem monhang nó có nằm trong gio hang chưa .
Le Dung said
Xu dung code nay thi ok nhung lam cach nao de remove mot mon hang va edit mon hang nhi. Can su tro giup
Thanks!
viet said
em thua thay em lam theo thay nhung em chuyen sang MS SQL no bao loi thay a
quyentv said
Thay oi thay co them vao phan dowload cac vi du duoc khong a , copy tat ca ve roi xem thi de hieu hon la nhin tung chut 1 . Cam on thay vi da chia se
hieu said
cám ơn…!
hieu said
Cám ơn thầy, bài viết rất hay ^^!
Quoc Anh said
Cám ơn thầy. Ví dụ demo rất rõ ràng và dễ hiểu.
kimthuy said
Bài viết rất hay, rất bổ ích, Cảm ơn tác giả.
Đường mòn said
Giạ cho em hỏi,em làm sao ma bị lỗi như sau.đây là bài làm theo kiểu Structs lần thứ 2 liên tiếp em điều bị lỗi như vậy:
em dùng netbean7.0.1,cài đặt jdk 1.7 và sử dụng GlassFish 3.1
THÔNG BÁO LỖI:
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
root cause
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.1 logs.
GlassFish Server Open Source Edition 3.1.1
hythinh said
Cám ơn thầy, bài viết rất dễ hiểu