PageHelper分頁

環(huán)境:springboot+mybatis+maven+yaml配置+前端用thymleaf模板(其實(shí)環(huán)境不太一樣也可以,我覺得我這種方法很簡單)

1.pom.xml添加依賴
<dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper-spring-boot-starter</artifactId>
          <version>1.2.13</version>
</dependency>
2.配置application.yaml
#配置分頁
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
3.controller寫分頁代碼
  1. currentPage是當(dāng)前頁,pageSize是當(dāng)前頁的限制大小
  2. List<Type> list = typeService.listPage();是從數(shù)據(jù)庫中獲取所有的數(shù)據(jù)行,這個(gè)時(shí)候還沒有分頁。
  3. 然后如果list!=null。這個(gè)時(shí)候就把list放到PageInfo類型的變量中,然后才從PageInfo中獲得list,就完成了分頁。
  4. 把list返回前端。
@RequestMapping("/type")
    public ModelAndView getTypes(@RequestParam(defaultValue = "1") Integer currentPage,
                                   @RequestParam(defaultValue = "1") Integer pageSize){
            ModelAndView model = new ModelAndView();
            //1.開啟分頁
            PageHelper.startPage(currentPage,pageSize);
            List<Type> list = typeService.listPage();
            //封裝list到PageInfo對(duì)象中,自動(dòng)分頁
            PageInfo<Type> typePageInfo = null;
            if(list!=null){
                typePageInfo =  new PageInfo<>(list);
                list = typePageInfo.getList();
            }
            model.addObject("list",list);
            model.setViewName("admin/types");
            return model;
        }
4.前端
       <table >
            <thead>
            <tr><th>名稱</th>
                <th>操作</th>
            </tr></thead>
            <tbody>
            <tr th:each="temp: ${list}">
                <td th:text="${temp.name}"></td>
                <td>
                    <a href="#" class="ui mini teal basic button">編輯</a>
                    <a href="#" class="ui mini red basic button">刪除</a>
                </td>
            </tr>
            </tbody>
        </table>
5.結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容