Web bán hàng bằng Spring MVC – Hiển thị sản phẩm và chi tiết sản phẩm

Tiếp tục loạt bài hướng dẫn xây dựng Web bán hàng bằng Spring MVC thì Team Việt Dev sẽ trình bày phần hiển thị danh sách sản phẩm và chi tiết sản phẩm từ cơ sử dữ liệu lên website.

Phần trước chúng ta đã hoàn thành phần thiết kế giao diện trang bán hàng, hiển thị danh mục sản phẩm thì phần tiếp theo sẽ tiếp tục thực hiện thị sản phẩm và thông tin chi tiết từ cơ sở dữ liệu lên web.

Yêu cầu:

Bước 1: Viết các phương thức CRUD của sản phẩm.

Lớp ProductDAO.java:

package com.teamvietdev.dao;

import com.teamvietdev.model.Product;
import java.util.List;

/**
 *
 * @author TVD
 */
public interface ProductDAO {

    // create
    public boolean create(Product object);

    // update
    public boolean update(Product object);

    // delete
    public boolean delete(Product object);

    // find by id
    public Product findById(long productId);

    // load list product by category
    public List<Product> getListByCategory(long categoryId);

    // load list product by category and limit
    public List<Product> getListByCategoryAndLimit(long categoryId, int limit);

    // load list product by featured
    public List<Product> getListFeatured(int limit);

    // load list product by sale
    public List<Product> getListSale(int limit);

    // load list product by nav
    public List<Product> getListNav(int start, int limit);

}

Lớp ProductDAOImpl.java:

package com.teamvietdev.dao;

import com.teamvietdev.model.Product;
import com.teamvietdev.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

/**
 *
 * @author TVD
 */
@Repository
public class ProductDAOImpl implements ProductDAO {

    @Override
    public boolean create(Product object) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(object);
            transaction.commit();
            return true;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return false;
    }

    @Override
    public boolean update(Product object) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.update(object);
            transaction.commit();
            return true;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return false;
    }

    @Override
    public boolean delete(Product object) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.delete(object);
            transaction.commit();
            return true;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return false;
    }

    @Override
    public Product findById(long productId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product WHERE productId = :productId");
            query.setLong("productId", productId);
            Product obj = (Product) query.uniqueResult();
            transaction.commit();
            return obj;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

    @Override
    public List<Product> getListByCategory(long categoryId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product WHERE categoryId = :categoryId");
            query.setLong("categoryId", categoryId);
            List<Product> list = query.list();
            transaction.commit();
            return list;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

    @Override
    public List<Product> getListByCategoryAndLimit(long categoryId, int limit) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product WHERE categoryId = :categoryId");
            query.setLong("categoryId", categoryId);
            query.setMaxResults(limit);
            List<Product> list = query.list();
            transaction.commit();
            return list;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

    @Override
    public List<Product> getListFeatured(int limit) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product ORDER BY productView DESC");
            query.setMaxResults(limit);
            List<Product> list = query.list();
            transaction.commit();
            return list;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

    @Override
    public List<Product> getListSale(int limit) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product ORDER BY productSale DESC");
            query.setMaxResults(limit);
            List<Product> list = query.list();
            transaction.commit();
            return list;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

    @Override
    public List<Product> getListNav(int start, int limit) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Query query = session.createQuery("FROM product");
            query.setMaxResults(limit);
            List<Product> list = query.list();
            transaction.commit();
            return list;
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }

}

Lớp ProductService.java:

package com.teamvietdev.service;

import com.teamvietdev.model.Product;
import java.util.List;

/**
 *
 * @author TVD
 */
public interface ProductService {

    // create
    public boolean create(Product object);

    // update
    public boolean update(Product object);

    // delete
    public boolean delete(Product object);

    // find by id
    public Product findById(long productId);

    // load list product by category
    public List<Product> getListByCategory(long categoryId);

    // load list product by featured
    public List<Product> getListFeatured(int limit);

    // load list product by sale
    public List<Product> getListSale(int limit);

    // load list product by nav
    public List<Product> getListNav(int start, int limit);

}

Lớp ProductServiceImpl.java:

package com.teamvietdev.service;

import com.teamvietdev.dao.ProductDAO;
import com.teamvietdev.model.Product;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author TVD
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDAO productDAO;

    @Override
    public boolean create(Product object) {
        return productDAO.create(object);
    }

    @Override
    public boolean update(Product object) {
        return productDAO.update(object);
    }

    @Override
    public boolean delete(Product object) {
        return productDAO.delete(object);
    }

    @Override
    public Product findById(long categoryId) {
        return productDAO.findById(categoryId);
    }

    @Override
    public List<Product> getListByCategory(long categoryId) {
        return productDAO.getListByCategory(categoryId);
    }

    @Override
    public List<Product> getListFeatured(int limit) {
        return productDAO.getListFeatured(limit);
    }

    @Override
    public List<Product> getListSale(int limit) {
        return productDAO.getListSale(limit);
    }

    @Override
    public List<Product> getListNav(int start, int limit) {
        return productDAO.getListNav(start, limit);
    }

}

Vào tập tin dispatcher-servlet.xml và thêm đoạn mã sau:

<bean id="productDAO" class="com.teamvietdev.dao.ProductDAOImpl" />
<bean id="productService" class="com.teamvietdev.service.ProductServiceImpl" />

Cấu trúc thư mục bố trí như sau:

Web bán hàng bằng Spring MVC – Hiển thị sản phẩm và chi tiết sản phẩm

Bước 3: Bây giờ chúng ta sẽ hiển thị sản phẩm, bạn mở lớp ControllerPages.java

package com.teamvietdev.controller;

import com.teamvietdev.service.CategoryService;
import com.teamvietdev.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author TVD
 */
@Controller
@RequestMapping(value = "")
public class ControllerPages {
    
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductService productService;
    
    @RequestMapping(value = "home.html", method = RequestMethod.GET)
    public String viewHome(ModelMap mm) {
        mm.put("listCategory", categoryService.getAll());
        mm.put("listProductFeatured", productService.getListFeatured(4));
        mm.put("listProductSale", productService.getListSale(4));
        return "pages/index";
    }
    
}

Hiển thị sản phẩm trên trang chủ như là danh sách sản phẩm nổi bật, danh sách sản phẩm giảm giá, mở tập tin content.jsp và sửa mã thành:

<%-- 
    Document   : content
    Created on : 24-Nov-2018, 10:58:42 AM
    Author     : TVD
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>content</title>
    </head>
    <body>

        <div class="container">
            <div class="content">
                <div class="content-top">
                    <h3 class="future">FEATURED </h3>
                    <div class="content-top-in">
                        <c:forEach var="item" items="${listProductFeatured}">
                            <div class="col-md-3 md-col">
                                <div class="col-md">
                                    <a href="single.html"><img  src="${pageContext.request.contextPath}/resources/pages/images/pi.jpg" alt="" /></a>	
                                    <div class="top-content">
                                        <h5><a href="single.html">${item.productName}</a></h5>
                                        <div class="white">
                                            <a href="single.html" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2 ">ADD TO CART</a>
                                            <p class="dollar"><span class="in-dollar">$</span><span>${item.productPrice}</span></p>
                                            <div class="clearfix"></div>
                                        </div>
                                    </div>							
                                </div>
                            </div>
                        </c:forEach>
                        <div class="clearfix"></div>
                    </div>
                </div>

                <!---->
                <div class="content-top">
                    <h3 class="future">SALE </h3>
                    <div class="content-top-in">
                        <c:forEach var="item" items="${listProductSale}">
                        <div class="col-md-3 md-col">
                            <div class="col-md">
                                <a href="single.html"><img src="${pageContext.request.contextPath}/resources/pages/images/pi.jpg" alt="" /></a>	
                                <div class="top-content">
                                    <h5><a href="${pageContext.request.contextPath}/product/${item.productUrl}/${item.productId}.html">${item.productName}</a></h5>
                                    <div class="white">
                                        <a href="${pageContext.request.contextPath}/product/${item.productUrl}/${item.productId}.html" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2 ">ADD TO CART</a>
                                        <p class="dollar"><span class="in-dollar">$</span><span>${item.productPrice}</span></p>
                                        <div class="clearfix"></div>
                                    </div>
                                </div>							
                            </div>
                        </div>
                        </c:forEach>
                        <div class="clearfix"></div>
                    </div>
                </div>

            </div>
        </div>

    </body>
</html>

Kết quả sau khi thực hiện:

Web bán hàng bằng Spring MVC – Hiển thị sản phẩm và chi tiết sản phẩm

Hiển thị danh sách sản phẩm theo từng danh mục cụ thể, bạn mở lớp ControllerPages.java:

@RequestMapping(value = "category/{categoryUrl}/{categoryId}.html", method = RequestMethod.GET)
public String viewCategory(ModelMap mm, @PathVariable("categoryUrl") String categoryUrl, @PathVariable("categoryId") long categoryId) {
      mm.put("listCategory", categoryService.getAll());
      mm.put("listProduct", productService.getListByCategory(categoryId));
      return "pages/shop";
}

Mở tập tin shop.jsp và sửa mã thành:

<%-- 
    Document   : shop
    Created on : 24-Nov-2018, 11:22:53 AM
    Author     : TVD
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>shop</title>
    </head>
    <body>

        <jsp:include page="header.jsp"></jsp:include>

            <div class="container">
                <div class="products">
                    <h2 class=" products-in">PRODUCTS</h2>
                    
                    <c:set var="salary" scope="session" value="0"/>
                    <c:forEach var="item" items="${listProduct}">
                        <c:set var="salary" scope="session" value="${salary + 1}"/>
                        <c:if test = "${salary == 1}">
                            <div class=" top-products">
                        </c:if>
                        
                        <div class="col-md-3 md-col">
                            <div class="col-md">
                                <a href="single.html" class="compare-in"><img  src="images/pic.jpg" alt="" />
                                    <div class="compare">
                                        <span>Add to Compare</span>
                                        <span>Add to Whislist</span>
                                    </div>
                                </a>	
                                <div class="top-content">
                                    <h5><a href="single.html">${item.productName}</a></h5>
                                    <div class="white">
                                        <a href="single.html" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2">ADD TO CART</a>
                                        <p class="dollar"><span class="in-dollar">$</span><span>2</span><span>0</span></p>
                                        <div class="clearfix"></div>
                                    </div>
                                </div>							
                            </div>
                        </div>        
                                
                        <c:if test = "${salary == 4}">
                            <c:set var="salary" scope="session" value="0"/>
                            <div class="clearfix"></div>
                            </div>
                        </c:if>
                    </c:forEach>
                    
                <div class="clearfix"></div>    
                </div>
            </div>

        <jsp:include page="footer.jsp"></jsp:include>

    </body>
</html>

Kết quả sau khi thực hiện:

Web bán hàng bằng Spring MVC – Hiển thị sản phẩm và chi tiết sản phẩm

Hiển thị thông tin chi tiết từng sản phẩm, bạn mở lớp ControllerPages.java:

@RequestMapping(value = "product/{productUrl}/{productId}.html", method = RequestMethod.GET)
public String viewProduct(ModelMap mm, @PathVariable("productUrl") String productUrl, @PathVariable("productId") long productId) {
      mm.put("product", productService.findById(productId));
      return "pages/single";
}

Mở tập tin single.jsp và sửa mã thành:

<%-- 
    Document   : single
    Created on : 24-Nov-2018, 11:27:07 AM
    Author     : TVD
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>single</title>
    </head>
    <body>

        <jsp:include page="header.jsp"></jsp:include>

            <div class="container">
                <div class="single">
                    <div class="col-md-9 top-in-single">
                        <div class="col-md-5 single-top">
                            <img class="img-responsive fashion" src="${pageContext.request.contextPath}/resources/pages/images/si.jpg" alt="">
                    </div>	
                    <div class="col-md-7 single-top-in">
                        <div class="single-para">
                            <h4>${product.productName}</h4>
                            <h5>${product.productStatus}</h5>
                            <div class="available">
                                <h6>Available Options :</h6>
                                <ul>
                                    <li>Color:
                                        <select>
                                            <option>Silver</option>
                                            <option>Black</option>
                                            <option>Dark Black</option>
                                            <option>Red</option>
                                        </select></li>
                                    <li>Size:<select>
                                            <option>Large</option>
                                            <option>Medium</option>
                                            <option>small</option>
                                            <option>Large</option>
                                            <option>small</option>
                                        </select></li>
                                    <li>Quality:<select>
                                            <option>1</option>
                                            <option>2</option>
                                            <option>3</option>
                                            <option>4</option>
                                            <option>5</option>
                                        </select></li>
                                </ul>
                            </div>
                            <div class="para-grid">
                                <span  class="add-to">$${product.productPrice}</span>
                                <a href="#" class="hvr-shutter-in-vertical cart-to">Add to Cart</a>					
                                <div class="clearfix"></div>
                            </div>
                            <p>${product.productDescription}</p>
                        </div>
                    </div>
                    <div class="clearfix"> </div>
                    <div class="content-top-in">
                        <div class="col-md-4 top-single">
                            <div class="col-md">
                                <img  src="${pageContext.request.contextPath}/resources/pages/images/pic8.jpg" alt="" />	
                                <div class="top-content">
                                    <h5>Mascot Kitty - White</h5>
                                    <div class="white">
                                        <a href="#" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2">ADD TO CART</a>
                                        <p class="dollar"><span class="in-dollar">$</span><span>2</span><span>0</span></p>
                                        <div class="clearfix"></div>
                                    </div>
                                </div>							
                            </div>
                        </div>
                        <div class="col-md-4 top-single">
                            <div class="col-md">
                                <img  src="${pageContext.request.contextPath}/resources/pages/images/pic9.jpg" alt="" />	
                                <div class="top-content">
                                    <h5>Mascot Kitty - White</h5>
                                    <div class="white">
                                        <a href="#" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2">ADD TO CART</a>
                                        <p class="dollar"><span class="in-dollar">$</span><span>2</span><span>0</span></p>
                                        <div class="clearfix"></div>
                                    </div>
                                </div>							
                            </div>
                        </div>
                        <div class="col-md-4 top-single-in">
                            <div class="col-md">
                                <img  src="${pageContext.request.contextPath}/resources/pages/images/pic10.jpg" alt="" />	
                                <div class="top-content">
                                    <h5>Mascot Kitty - White</h5>
                                    <div class="white">
                                        <a href="#" class="hvr-shutter-in-vertical hvr-shutter-in-vertical2">ADD TO CART</a>
                                        <p class="dollar"><span class="in-dollar">$</span><span>2</span><span>0</span></p>
                                        <div class="clearfix"></div>
                                    </div>
                                </div>							
                            </div>
                        </div>

                        <div class="clearfix"></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="single-bottom">
                        <h4>Categories</h4>
                        <ul>
                            <li><a href="#"><i> </i>Fusce feugiat</a></li>
                            <li><a href="#"><i> </i>Mascot Kitty</a></li>
                            <li><a href="#"><i> </i>Fusce feugiat</a></li>
                            <li><a href="#"><i> </i>Mascot Kitty</a></li>
                            <li><a href="#"><i> </i>Fusce feugiat</a></li>
                        </ul>
                    </div>
                    <div class="single-bottom">
                        <h4>Product SALE</h4>
                        <div class="product">
                            <img class="img-responsive fashion" src="${pageContext.request.contextPath}/resources/pages/images/st1.jpg" alt="">
                            <div class="grid-product">
                                <a href="#" class="elit">Consectetuer adipiscing elit</a>
                                <span class="price price-in"><small>$500.00</small> $400.00</span>
                            </div>
                            <div class="clearfix"> </div>
                        </div>
                        <div class="product">
                            <img class="img-responsive fashion" src="${pageContext.request.contextPath}/resources/pages/images/st2.jpg" alt="">
                            <div class="grid-product">
                                <a href="#" class="elit">Consectetuer adipiscing elit</a>
                                <span class="price price-in"><small>$500.00</small> $400.00</span>
                            </div>
                            <div class="clearfix"> </div>
                        </div>
                        <div class="product">
                            <img class="img-responsive fashion" src="${pageContext.request.contextPath}/resources/pages/images/st3.jpg" alt="">
                            <div class="grid-product">
                                <a href="#" class="elit">Consectetuer adipiscing elit</a>
                                <span class="price price-in"><small>$500.00</small> $400.00</span>
                            </div>
                            <div class="clearfix"> </div>
                        </div>
                    </div>
                </div>
                <div class="clearfix"> </div>
            </div>
        </div>

        <jsp:include page="footer.jsp"></jsp:include>

    </body>
</html>

Kết quả sau khi thực hiện:

Web bán hàng bằng Spring MVC – Hiển thị sản phẩm và chi tiết sản phẩm

 

Lời kết: Trong thời gian tới Team Việt Dev sẽ tiếp tục chia sẻ thêm nhiều bài viết trong loạt bài hướng dẫn xây dựng web bán hàng bằng Spring MVC… miễn phí đến bạn đọc, các bạn nhớ theo dõi kênh để có được những chia sẻ mới nhất.

(Tác giả: Team Việt Dev)

4 Comments

  1. Nguyễn đa Min 19/10/2019 Reply
  2. Nguyen Tien Dat 04/01/2020 Reply
  3. hai 19/06/2020 Reply
  4. hai 19/06/2020 Reply

Bình luận