分散式電商專案(04)--商品列表查詢及分頁
前言:前面寫了後天管理系統工程搭建以及框架的整合測試,今天寫一下商品列表的分頁查詢
1 需求分析
前臺使用easyui的分頁工具,後臺則使用mybatis分頁外掛pagehelper
如上圖所示,開啟後臺首頁,點選查詢商品,按下F12,可以看到easyui的分頁介面會向controller傳送兩個資料page:1,rows:30
controller通過service層以及dao層查詢到資料之後也需要將資料封裝成easyui需要的格式,而easyui需要的資料格式如下
{ total:"2", rows:[ {"id":"1","name":"username1"}, {"id":"2","name":"username2"} ] }
對應現在的場景就是將資料封裝成total:商品總數,rows:商品資訊列表的格式
2 具體實現
2.1 封裝通用的分頁工具類
由於分頁在後面肯定還會用到,現在在common工程下寫一個easyui分頁的工具類,具體的程式碼如下:
public class EUDataGridResult { private long total; private List<?> rows; public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public List<?> getRows() { return rows; } public void setRows(List<?> rows) { this.rows = rows; } }
2.2 編寫介面及其實現類
在service工程下編寫service類及其實現類
ItemService的程式碼如下:
public interface ItemService { EUDataGridResult getItemList(Integer page, Integer rows); }
ItemServiceImpl的程式碼如下:
@Service public class ItemServiceImpl implements ItemService { @Autowired private TbItemMapper itemMapper; /** * 商品列表查詢 * @param page * @param rows * @return */ @Override public EUDataGridResult getItemList(Integer page, Integer rows) { TbItemExample example =new TbItemExample(); PageHelper.startPage(page,rows); List<TbItem> list = itemMapper.selectByExample(example); EUDataGridResult result = new EUDataGridResult(); result.setRows(list); PageInfo<TbItem> info = new PageInfo<>(list); result.setTotal(info.getTotal()); return result; } }
2.3 編寫Controller
ItemController的程式碼如下:
package com.taotao.controller; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.taotao.pojo.EUDataGridResult; import com.taotao.pojo.TaotaoResult; import com.taotao.pojo.TbItem; import com.taotao.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class ItemController { @Autowired private ItemService itemService; /** * 商品列表查詢 * @param page * @param rows * @return */ @RequestMapping("/item/list") @ResponseBody public EUDataGridResult getItemList(Integer page, Integer rows ){ EUDataGridResult result = itemService.getItemList(page, rows); return result; } }
此處要注意,RequestMapping中的值一定要與jsp頁面中的請求的值是一致的
3 測試
執行專案,點選查詢商品可以查詢出商品列表即為成功,即出現如下圖所示的介面:
4 相關檔案
下面提供一些相關的資源下載,包括後臺管理系統的靜態資源,博主使用的本地倉庫等
連結:https://pan.baidu.com/s/1mWDQznk0N5um_YMB7Greiw
提取碼:1gh3