CShop Project 06: 建立表對應的資料模型類 & Service和Dao層的商品查詢方法
阿新 • • 發佈:2020-08-23
一. 建立表對應的資料模型類
在com.Jasper2003.model包下,新增資料模型:
1. Goods.java
2. Type.java
3. Recommend.java
二. 建立Service和Dao層的熱銷商品查詢方法
<1> Dao層 -獲取資料
public class GoodsDao { public List<Map<String, Object>> getHotGoodsList() throws SQLException { QueryRunner r = new QueryRunner(DBUtil.getDataSource()); String sql= "select g.id,g.name,g.cover,g.price,t.name typename from recommend r,goods g,type t where type=2 and r.goods_id=g.id and g.type_id=t.id"; return r.query(sql,new MapListHandler()); } }
<2> Service層 -呼叫Dao層的查詢方法 (由於邏輯比較簡單, 故直接呼叫Dao層的方法)
public class GoodsService { private GoodsDao gDao = newGoodsDao();
public List<Map<String, Object>> getHotGoodsList() { List<Map<String, Object>> list = null; try { list = gDao.getHotGoodsList(); } catch (SQLException e) { e.printStackTrace(); } return list; } }
三. 在Servlet呼叫Service
在IndexServlet.java中:
protected void doGet() { // 取得熱銷商品 List<Map<String, Object>> list = gService.getHotGoodsList(); request.setAttribute("hotList", list); }
四. 在頁面端取得資料, 並展示在頁面上
在index.jsp中:
<div class="alert alert-danger">熱銷推薦</div> <div class="gallery-grids"> <c:forEach items="${hotList}" var="g"> <div class="col-md-4 gallery-grid glry-two"> <a href="detail.action?goodid=6"> <img src="${pageContext.request.contextPath }${g.cover}" class="img-responsive" alt="${g.name}" width="350" height="350"/> </a> <div class="gallery-info galrr-info-two"> <p> <span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> <a href="detail.action?goodid=6">檢視詳情</a> </p> <a class="shop" href="javascript:;" onclick="buy(6)">立刻購買</a> <div class="clearfix"> </div> </div> <div class="galy-info"> <p>${g.typeName } > ${g.name }</p> <div class="galry"> <div class="prices"> <h5 class="item_price">¥ ${g.price }</h5> </div> <div class="clearfix"></div> </div> </div> </div> </c:forEach> </div>
效果 (http://localhost:8080/web06_cakeshop/)
此時,熱銷商品是"動態"的,隨著資料庫的改動而改動