zoukankan      html  css  js  c++  java
  • [置顶] mybatis分页插件实现分页

    1.了解过程:在数据库服务器中,sql语句实现分页便要每个查询语句都要写上limit(开始,结束),并且不能灵活的随前端变化,为此使用拦截器的方法,过程:拦截器拦截请求的sql语句(根据需要拦截的ID(正则匹配),进行拦截),并对根据前端传过来的页数,和每页的条数,计算出limit(开始,结束),总条数,然后,拼接到sql语句后边。其中这个处理过程,已经封装到了,分页插件中,可以不用理解,直接使用。
    条件:maven下:
    1.pom.xml中导入依赖:

    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>4.1.4</version>
    </dependency>

    2.在mybatis-conf.xml中添加拦截器:

    <plugins>
            <plugin interceptor="com.github.pagehelper.PageHelper">
                <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->        
                <property name="dialect" value="mysql"/>
            </plugin>
        </plugins>

    3.编写page实例:

    package com.tc.tccp.core.page;
    
    /** 
     * @author wangpei 
     * @version 
     *创建时间:2016年10月12日 下午10:52:29 
     * 拦截器实现mybatis的拦截
     */
    import java.util.List;
    
    public class PageParameter {
    
        public static final int DEFAULT_PAGE_SIZE = 10;
    
        private int pageSize;// 页面大小
        private int currentPage;// 当前页的位置
        private int prePage;// 上一页
        private int nextPage;// 下一页
        private int totalPage;// 总页数
        private int totalCount;// 总条数
        /**
         * 当前页的数据
         */
        private List<?> list;
    
        /**
         * 获得分页内容
         *
         * @return
         */
        public List<?> getList() {
            return list;
        }
    
        public PageParameter(int pageSize, int currentPage, int prePage,
                int nextPage, int totalPage, int totalCount, List<?> list) {
            this.pageSize = pageSize;
            this.currentPage = currentPage;
            this.prePage = prePage;
            this.nextPage = nextPage;
            this.totalPage = totalPage;
            this.totalCount = totalCount;
            this.list = list;
        }
    
        /**
         * 设置分页内容
         *
         * @param list
         */
        @SuppressWarnings("unchecked")
        public void setList(List list) {
            this.list = list;
        }
    
        public PageParameter() {
            this.currentPage = 1;
            this.pageSize = DEFAULT_PAGE_SIZE;
        }
    
        /**
         *
         * @param currentPage
         * @param pageSize
         */
        public PageParameter(int currentPage, int pageSize) {
            this.currentPage = currentPage;
            this.pageSize = pageSize;
        }
    
        public int getCurrentPage() {
            return currentPage;
        }
    
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
    
        public int getPageSize() {
            return pageSize;
        }
    
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
    
        public int getPrePage() {
            return prePage;
        }
    
        public void setPrePage(int prePage) {
            this.prePage = prePage;
        }
    
        public int getNextPage() {
            return nextPage;
        }
    
        public void setNextPage(int nextPage) {
            this.nextPage = nextPage;
        }
    
        public int getTotalPage() {
            return totalPage;
        }
    
        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }
    
        public int getTotalCount() {
            return totalCount;
        }
    
        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }
    
        public String toString() {
            return "pageSize=" + pageSize + "currentPage=" + currentPage
                    + "prePage=" + prePage + "nextPage=" + nextPage + "totalPage="
                    + totalPage + "totalCount=" + totalCount;
        }
    
    }
    

    4.编写操做的dao层,和dao.xml
    其中,需要拦截的方法,需要以ID(正则匹配),我以.page结尾。
    这里写图片描述
    5.controller层

        @RequestMapping("getAll")
        @ResponseBody
        public Map<String, Object> get(HttpServletRequest request,HttpServletResponse response, Integer page/* 当前页 */, Integer rows/* 每页显示的数量 */) {
            // 当前页
            int intPage = page == null ||  page <= 0 ? 1 : page;
            // 设置每页显示的数量
            int intPageSize = rows == null || rows <= 0 ? 10 : rows;
            PageParameter page1 = new PageParameter();
            System.out.println("当前页="+intPage);
            System.out.println("一页的条数="+intPageSize);
            page1.setCurrentPage(intPage);
            page1.setPageSize(intPageSize);
            PageHelper.startPage(intPage, intPageSize);
            List<Studio> d = studioService.findAllStudioByPage(page1); // 取商品列表
            PageInfo<Studio> pageInfo = new PageInfo<Studio>(d);
            Map<String, Object> reMap = new HashMap<String, Object>();
            // 取分页信息
            reMap.put("total", pageInfo.getTotal()); // 总条数
            reMap.put("pageSize", intPageSize); // 每页显示的数量
            reMap.put("pageNo", intPage); // 当前页数
            reMap.put("rows", d); // 从数据库中获取的列表信息
    
            return reMap;
        }

    将获取到的查新结果放入reMap,然后前端获取到reMap的值,类似json格式的数据。

    前端jsp页面自己完成,我是用easyui做的,

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%
        String path = request.getContextPath();
        //System.out.println("path===" + path);
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>LayOut</title>
     <script src="<%=request.getContextPath()%>/css/easyui/jquery.min.js" type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/css/easyui/jquery.easyui.min.js" type="text/javascript"></script>
    <link href="<%=request.getContextPath()%>/css/easyui/themes/default/easyui.css" rel="stylesheet"ntype="text/css" />
    <link href="<%=request.getContextPath()%>/css/easyui/themes/icon.css" rel="stylesheet" type="text/css" /> 
    <script type="text/javascript">
        $(function() {
        $('#dg').datagrid({
                title : '结果列表',
                pageSize : 10,//默认选择的分页是每页10行数据
                pageList : [ 5, 10, 15, 20 ],//可以选择的分页集合
                nowrap : true,//设置为true,当数据长度超出列宽时将会自动截取
                striped : true,//设置为true将交替显示行背景。
                collapsible : true,//显示可折叠按钮
    
                url : '/tccp/studio/getAll',//url调用Action方法
                loadMsg : '数据装载中......',
                singleSelect : false,//为true时只能选择单行
                fitColumns : false,
                remoteSort : false,
                onClickRow : function(rowIndex, rowData) {//单击事件
                },
                onDblClickRow : function(rowIndex, rowData) {//双击事件
                },
    
                toolbar : [ {// 工具栏  
                    text : '添加',  
                    iconCls : 'icon-add', // 图标  
                    handler : function() { // 处理函数  
                        addBook();  
                    }  
                }, {  
                    text : '删除',  
                    iconCls : 'icon-cancel', // 图标  
                    handler : function() { // 处理函数  
                        deleteBook();  
                    }  
                }, {  
                    text : '编辑',  
                    iconCls : 'icon-edit',// 图标  
                    handler : function() {// 处理函数  
                        editBook();  
                    }  
                } ],  
    
                frozenColumns : [ [ {
                    field : 'id',
                    checkbox : true
                },  {
                    field : 'studio_id',
                    align : 'center',
                    title : '厅号',
                    width : 200
                }, {
                    field : 'studio_name',
                    align : 'center',
                    title : '厅名',
                    width : 200
                } ] ],
                columns : [ [ {
                    field : 'studio_row_count',
                    align : 'center',
                    title : '行数',
                    width : 200
                }, {
                    field : 'studio_col_count',
                    align : 'center',
                    title : '列数',
                    width : 200
                },{
                    field : 'studio_introduction',
                    align : 'center',
                    title : '介绍',
                    width : 200
                },{
                    field : 'studio_flag',
                    align : 'center',
                    title : '是否安排座位',
                    width : 220
                }] ],
                pagination : true,//分页
                rownumbers : true
            //行数
            });
            var p = $('#dg').datagrid('getPager');  
    
            $(p).pagination({  
                pageSize: 10,//每页显示的记录条数,默认为10   
                pageList: [5,10,15,20],//可以设置每页记录条数的列表   
                beforePageText: '第',//页数文本框前显示的汉字   
                afterPageText: '页    共 {pages} 页',   
                displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',   
            });
    
    
            //在datagrid实例化之后调用这个方法。
            $("#dg").datagrid({}).datagrid("page");
    
        });
    
    
    
    
        function showEditForm() {  
    
                $('#EditForm').form('submit', {
                    url: "/tccp/studio/add",
                    onSubmit: function () {               //表单提交前的回调函数
                        var isValid = $(this).form('validate');//验证表单中的一些控件的值是否填写正确,比如某些文本框中的内容必须是数字
                        if (!isValid) {
                        }
                        return isValid; // 如果验证不通过,返回false终止表单提交
                    },
                    success: function (data) {    //表单提交成功后的回调函数,里面参数data是我们调用/BasicClass/ModifyClassInfo方法的返回值。
                        if (data > 0) {
                            $.messager.show({
                                title: '提示消息',
                                msg: '提交成功',
                                showType: 'show',
                                timeout: 1000,
                                style: {
                                    right: '',
                                    bottom: ''
                                }
                            });
                            $('#dg').datagrid('reload');    // 重新载入当前页面数据  
                            $('#Editwin').window('close');  //关闭窗口
                        }
                        else {
                            $.messager.alert('提示信息', '提交失败,请联系管理员!', 'warning');
                    }
                    }
                });
        }  
    
        // 关闭窗口  
        function closeForm() {  
            $("#frmEdit").form('clear');  
            $('#tabEdit').dialog('close');  
        }  
        // 添加的函数  
        function addBook() {  
            // 清空原有的数据  
            $('#frmEdit').form('clear');  
            // 显示添加对话框  
            showEditForm();  
        }  
    
    
    </script>
    </head>
    
    <body class="easyui-layout" id="cc">
    
       <div id="tabEdit">  
                        <form id="frmEdit">  
                        <input type="hidden" id="id" name="book.id" />  
                        <dl>  
                            <dd>  
                                演出厅编号:  
                            </dd>  
                            <dd>  
                                <input type="text" style=" 150px" id="isbn" name="studioId" />  
                            </dd>  
                        </dl>  
                        <dl>  
                            <dd>  
                                演出厅名称:  
                            </dd>  
                            <dd>  
                                <input type="text" style=" 150px" id="title" name="studioName" />  
                            </dd>  
                        </dl>  
                        <dl>  
                            <dd>  
                                演出厅行号:  
                            </dd>  
                            <dd>  
                                <input type="text" style=" 150px" id="price" name="studioRow" />  
                            </dd>  
                        </dl>  
                        <dl>  
                            <dd>  
                                演出厅列号:  
                            </dd>  
                            <dd>  
                                <input type="text" style=" 150px" id="pubdate" name="studioCol" />  
                            </dd>  
                        </dl>  
                        <dl>  
                            <dd>  
                                是否安排座位:  
                            </dd>  
                            <dd>  
                                <input type="text" style=" 150px" id="pubdate" name="flag" />  
                            </dd>  
                        </dl>  
                        <dl>  
                            <dd>  
                                演出厅介绍:  
                            </dd>  
                            <dd>  
                                <textarea cols="45" rows="3" id="intro" name="studioIntroduce"></textarea>  
                            </dd>  
                        </dl>  
                        </form>  
                    </div>  
    
    <div region="north" border="true" split="true"
            style="overflow: hidden; height: 65px;">
            <form id="searchForm" name="searchForm">
                <table id="searchTable" width=100%>
                    <tr>    
                        <td>当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">影厅管理</a> &gt; 内容列表<!--   <input class="easyui-textbox" type="text" name="bh"  id="bh">--></td>
                                &nbsp;&nbsp;&nbsp;      
                        <td>厅名:<input class="easyui-textbox" type="text" name="bjmc" id="bjmc">&nbsp;<a href="#" class="easyui-linkbutton" icon="icon-search"
                            onclick="doSearch()">查询</a>
                        </td>
                        <td>
                        &nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
                          <td><a href="#" class="easyui-linkbutton" icon="icon-search"
                            onclick="doSearch()">退出</a>
                        </td>                       
                    </tr>
                </table>
    
            </form>
        </div>
        <div region="center" border="true" split="true"
            style="overflow: hidden;">
            <table id="dg" title="My Users" class="easyui-datagrid" width="100%"
                height="99%" toolbar="#toolbar" rownumbers="true" fitColumns="true"
                singleSelect="true">
    
            </table>
    
    
        </div>
    
    
    
    
    
    </body>
    </html>

    代码写的有点乱,我会继续改的,原谅小白一枚!!!!,有什么问题就问,要源码的,都可以。

  • 相关阅读:
    IO流基础
    DB2 存储过程创建、系统表
    dubbo实现原理简单介绍
    Java 标准 I/O 介绍
    mysql由于权限问题看不到用户数据库
    java 字符常量池
    Java NIO:NIO概述
    128 C语言实现文件复制功能(包括文本文件和二进制文件)
    Linux 下各个目录的作用及内容
    Linux文件系统详解
  • 原文地址:https://www.cnblogs.com/wangxiaopei/p/8551181.html
Copyright © 2011-2022 走看看