spring mvc +bootstrap+datatable实现分页

钱焕
2023-12-01

文章介绍大致分以下几步:
1. 后台数据分页查询实现;
2. 前台bootstrap样式+datatable插件 数据渲染;

一、后台真分页实现:
主要涉及以下内容:
1、数据库分页插件类PagePlugin.java;
2、分页参数类Page.java;
3、排序类SortCond.java;
4、用来返回datatables格式数据的DataTables.java(不使用datatables时不需要);
5、mybatis-config.xml配置插件;
6、相关mapper.xml文件SQL;
7、controller层参数传递;
直接上代码:
1、PagePlugin.java

package com.bi.dao.base.plugin;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import com.bi.common.base.entity.Page;
import com.bi.common.util.ReflectHelper;
import com.bi.common.util.Tools;

/**
 * 
 * <p>功能描述:</p>
 * <p>Company: </p>
 * @author Jeff
 * @version 1.0 2015年12月9日
 */
@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PagePlugin implements Interceptor {

    private static String dialect = ""; //数据库方言
    private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)

    public Object intercept(Invocation ivk) throws Throwable {
        // TODO Auto-generated method stub
        if(ivk.getTarget() instanceof RoutingStatementHandler){
            RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
            MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");

            if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL
                BoundSql boundSql = delegate.getBoundSql();
                Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
                if(parameterObject==null){
                    throw new NullPointerException("parameterObject尚未实例化!");
                }else{
                    Connection connection = (Connection) ivk.getArgs()[0];
                    String sql = boundSql.getSql();
                    //String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
                    String countSql = "select count(0) from (" + sql+ ")  tmp_count"; //记录统计 == oracle 加 as 报错(SQL command not properly ended)
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
                    setParameters(countStmt,mappedStatement,countBS,parameterObject);
                    ResultSet rs = countStmt.executeQuery();
                    int count = 0;
                    if (rs.next()) {
                        count = rs.getInt(1);
                    }
                    rs.close();
                    countStmt.close();
                    //System.out.println(count);
                    Page page = null;
                    if(parameterObject instanceof Page){    //参数就是Page实体
                         page = (Page) parameterObject;
                         page.setEntityOrField(true);    
                        page.setTotalResult(count);
                    }else{  //参数为某个实体,该实体拥有Page属性
                        Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
                        if(pageField!=null){
                            page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
                            if(page==null)
                                page = new Page();
                            page.setEntityOrField(false); 
                            page.setTotalResult(count);
                            ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象
                        }else{
                            throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");
                        }
                    }
                    String pageSql = generatePageSql(sql,page);
                    ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.
                }
            }
        }
        return ivk.proceed();
    }


    /**
     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if (value != null) {
                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                        }
                    } else {
                        value = metaObject == null ? null : metaObject.getValue(propertyName);
                    }
                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
                }
            }
        }
    }

    /**
     * 根据数据库方言,生成特定的分页sql
     * @param sql
     * @param page
     * @return
     */
    private String generatePageSql(String sql,Page page){
        if(page!=null && Tools.notEmpty(dialect)){
            StringBuffer pageSql = new StringBuffer();
            if("mysql".equals(dialect)){
                pageSql.append(sql);
                pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());
            }else if("oracle".equals(dialect)){
                pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
                pageSql.append(sql);
                //pageSql.append(") as tmp_tb where ROWNUM<=");
                pageSql.append(") tmp_tb where ROWNUM<=");
                pageSql.append(page.getCurrentResult()+page.getShowCount());
                pageSql.append(") where row_id>");
                pageSql.append(page.getCurrentResult());
            }
            return pageSql.toString();
        }else{
            return sql;
        }
    }

    public Object plugin(Object arg0) {
        // TODO Auto-generated method stub
        return Plugin.wrap(arg0, this);
    }

    public void setProperties(Properties p) {
        dialect = p.getProperty("dialect");
        if (Tools.isEmpty(dialect)) {
            try {
                throw new PropertyException("dialect property is not found!");
            } catch (PropertyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        pageSqlId = p.getProperty("pageSqlId");
        if (Tools.isEmpty(pageSqlId)) {
            try {
                throw new PropertyException("pageSqlId property is not found!");
            } catch (PropertyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

2、Page.java

package com.bi.common.base.entity;

import com.bi.common.util.Const;
import com.bi.common.util.PageData;
import com.bi.common.util.Tools;

public class Page {
    private int showCount; // 每页显示记录数
    private int totalPage; // 总页数
    private int totalResult; // 总记录数
    private int currentPage; // 当前页
    private int currentResult; // 当前记录起始索引
    private boolean entityOrField; // true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性
    private String pageStr; // 最终页面显示的底部翻页导航,详细见:getPageStr();
    private PageData pd = new PageData();

    public Page() {
        try {
            this.showCount = Integer.parseInt(Tools.readTxtFile(Const.PAGE));
        } catch (Exception e) {
            this.showCount = 15;
        }
    }

    public int getTotalPage() {
        if (totalResult % showCount == 0)
            totalPage = totalResult / showCount;
        else
            totalPage = totalResult / showCount + 1;
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalResult() {
        return totalResult;
    }

    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }

    public int getCurrentPage() {
        if (currentPage <= 0)
            currentPage = 1;
        if (currentPage > getTotalPage())
            currentPage = getTotalPage();
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
        this.currentResult = (currentPage - 1) * getShowCount();
    }

    public String getPageStr() {
        StringBuffer sb = new StringBuffer();
        if (totalResult > 0) {
            sb.append(" <ul>\n");
            if (currentPage == 1) {
                sb.append(" <li><a>共<font color=red>" + totalResult
                        + "</font>条</a></li>\n");
                sb.append(" <li><input type=\"number\" value=\"\" id=\"toGoPage\" style=\"width:50px;text-align:center;float:left\" placeholder=\"页码\"/></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"toTZ();\"  class=\"btn btn-mini btn-success\">跳转</a></li>\n");
                sb.append(" <li><a>首页</a></li>\n");
                sb.append(" <li><a>上页</a></li>\n");
            } else {
                sb.append(" <li><a>共<font color=red>" + totalResult
                        + "</font>条</a></li>\n");
                sb.append(" <li><input type=\"number\" value=\"\" id=\"toGoPage\" style=\"width:50px;text-align:center;float:left\" placeholder=\"页码\"/></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"toTZ();\"  class=\"btn btn-mini btn-success\">跳转</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage(1)\">首页</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("
                        + (currentPage - 1) + ")\">上页</a></li>\n");
            }
            int showTag = 5;// 分页标签显示数量
            int startTag = 1;
            if (currentPage > showTag) {
                startTag = currentPage - 1;
            }
            int endTag = startTag + showTag - 1;
            for (int i = startTag; i <= totalPage && i <= endTag; i++) {
                if (currentPage == i)
                    sb.append("<li><a><font color='#808080'>" + i
                            + "</font></a></li>\n");
                else
                    sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("
                            + i + ")\">" + i + "</a></li>\n");
            }
            if (currentPage == totalPage) {
                sb.append(" <li><a>下页</a></li>\n");
                sb.append(" <li><a>尾页</a></li>\n");
            } else {
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("
                        + (currentPage + 1) + ")\">下页</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("
                        + totalPage + ")\">尾页</a></li>\n");
            }
            sb.append(" <li><a>第" + currentPage + "页</a></li>\n");
            sb.append(" <li><a>共" + totalPage + "页</a></li>\n");

            sb.append(" <li><select title='显示条数' style=\"width:55px;float:left;\" onchange=\"changeCount(this.value)\">\n");
            sb.append(" <option value='" + showCount + "'>" + showCount
                    + "</option>\n");
            sb.append(" <option value='10'>10</option>\n");
            sb.append(" <option value='20'>20</option>\n");
            sb.append(" <option value='30'>30</option>\n");
            sb.append(" <option value='40'>40</option>\n");
            sb.append(" <option value='50'>50</option>\n");
            sb.append(" <option value='60'>60</option>\n");
            sb.append(" <option value='70'>70</option>\n");
            sb.append(" <option value='80'>80</option>\n");
            sb.append(" <option value='90'>90</option>\n");
            sb.append(" <option value='99'>99</option>\n");
            sb.append(" </select>\n");
            sb.append(" </li>\n");

            sb.append("</ul>\n");
            sb.append("<script type=\"text/javascript\">\n");

            // 换页函数
            sb.append("function nextPage(page){");
            sb.append(" top.jzts();");
            sb.append(" if(true && document.forms[0]){\n");
            sb.append("     var url = document.forms[0].getAttribute(\"action\");\n");
            sb.append("     if(url.indexOf('?')>-1){url += \"&"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     url = url + page + \"&"
                    + (entityOrField ? "showCount" : "page.showCount") + "="
                    + showCount + "\";\n");
            sb.append("     document.forms[0].action = url;\n");
            sb.append("     document.forms[0].submit();\n");
            sb.append(" }else{\n");
            sb.append("     var url = document.location+'';\n");
            sb.append("     if(url.indexOf('?')>-1){\n");
            sb.append("         if(url.indexOf('currentPage')>-1){\n");
            sb.append("             var reg = /currentPage=\\d*/g;\n");
            sb.append("             url = url.replace(reg,'currentPage=');\n");
            sb.append("         }else{\n");
            sb.append("             url += \"&"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";\n");
            sb.append("         }\n");
            sb.append("     }else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     url = url + page + \"&"
                    + (entityOrField ? "showCount" : "page.showCount") + "="
                    + showCount + "\";\n");
            sb.append("     document.location = url;\n");
            sb.append(" }\n");
            sb.append("}\n");

            // 调整每页显示条数
            sb.append("function changeCount(value){");
            sb.append(" top.jzts();");
            sb.append(" if(true && document.forms[0]){\n");
            sb.append("     var url = document.forms[0].getAttribute(\"action\");\n");
            sb.append("     if(url.indexOf('?')>-1){url += \"&"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     url = url + \"1&"
                    + (entityOrField ? "showCount" : "page.showCount")
                    + "=\"+value;\n");
            sb.append("     document.forms[0].action = url;\n");
            sb.append("     document.forms[0].submit();\n");
            sb.append(" }else{\n");
            sb.append("     var url = document.location+'';\n");
            sb.append("     if(url.indexOf('?')>-1){\n");
            sb.append("         if(url.indexOf('currentPage')>-1){\n");
            sb.append("             var reg = /currentPage=\\d*/g;\n");
            sb.append("             url = url.replace(reg,'currentPage=');\n");
            sb.append("         }else{\n");
            sb.append("             url += \"1&"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";\n");
            sb.append("         }\n");
            sb.append("     }else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage")
                    + "=\";}\n");
            sb.append("     url = url + \"&"
                    + (entityOrField ? "showCount" : "page.showCount")
                    + "=\"+value;\n");
            sb.append("     document.location = url;\n");
            sb.append(" }\n");
            sb.append("}\n");

            // 跳转函数
            sb.append("function toTZ(){");
            sb.append("var toPaggeVlue = document.getElementById(\"toGoPage\").value;");
            sb.append("if(toPaggeVlue == ''){document.getElementById(\"toGoPage\").value=1;return;}");
            sb.append("if(isNaN(Number(toPaggeVlue))){document.getElementById(\"toGoPage\").value=1;return;}");
            sb.append("nextPage(toPaggeVlue);");
            sb.append("}\n");
            sb.append("</script>\n");
        }
        pageStr = sb.toString();
        return pageStr;
    }

    public void setPageStr(String pageStr) {
        this.pageStr = pageStr;
    }

    public int getShowCount() {
        return showCount;
    }

    public void setShowCount(int showCount) {

        this.showCount = showCount;
    }

    public int getCurrentResult() {
        currentResult = (getCurrentPage() - 1) * getShowCount();
        if (currentResult < 0)
            currentResult = 0;
        return currentResult;
    }

    public void setCurrentResult(int currentResult) {
        this.currentResult = currentResult;
        this.currentPage = (currentResult / showCount) + 1;
    }

    public boolean isEntityOrField() {
        return entityOrField;
    }

    public void setEntityOrField(boolean entityOrField) {
        this.entityOrField = entityOrField;
    }

    public PageData getPd() {
        return pd;
    }

    public void setPd(PageData pd) {
        this.pd = pd;
    }

}

3、SortCond.java

package com.bi.common.base.entity;

/**
 * <p>功能描述:排序类</p>
 * <p>Company: </p>
 * @author Jeff
 * @version 1.0 2015年12月11日
 */
public class SortCond {
    /**
     * 排序类型枚举
     */
    public enum Order {
        ASC, DESC
    }

    /**
     * 排序类型
     */
    private String column;

    /**
     * 排序类型
     */
    private Order order;

    public SortCond(String column) {
        this(column, Order.DESC);
    }

    public SortCond(String column, Order order) {
        this.column = column;
        this.order = order;
    }

    public String getColumn() {
        return column;
    }

    public Order getOrder() {
        return order;
    }
}

4、DataTables.java

/**
 * 文件名: DataTables.java
 * 版    权: Copyright © 2013 - 2015 ThinkJF, Inc. All Rights Reserved
 * 描    述: <描述>
 * 创建人: Jeff
 * 创建时间: 2015年12月10日
 */
package com.bi.common.base.entity;

import java.io.Serializable;
import java.util.List;

import org.apache.poi.ss.formula.functions.T;

/**
 * <p>功能描述:datatables数据返回实体类</p>
 * <p>Company: 上海丞风智能科技有限公司</p>
 * @author Jeff
 * @version 1.0 2015年12月10日
 */
public class DataTables<T> implements Serializable{

    private static final long serialVersionUID = 8172262630982712326L;
    //与datatales 加载的“dataSrc"对应  
    private List<T> data; 
    //过滤后的记录数
    private int recordsFiltered;   
    //数据库里总共记录数
    private int recordsTotal;
    //请求次数计数器
    private int draw;

    private Boolean success;


    public List<T> getData() {
        return data;
    }
    public void setData(List<T> data) {
        this.data = data;
    }
    public int getRecordsFiltered() {
        return recordsFiltered;
    }
    public void setRecordsFiltered(int recordsFiltered) {
        this.recordsFiltered = recordsFiltered;
    }
    public int getRecordsTotal() {
        return recordsTotal;
    }
    public void setRecordsTotal(int recordsTotal) {
        this.recordsTotal = recordsTotal;
    }
    public int getDraw() {
        return draw;
    }
    public void setDraw(int draw) {
        this.draw = draw;
    }



}

5、mybatis-config.xml配置插件
指定方言为mysql,且配置sqlid以_page结尾的都走分页查询

    <plugins>
        <plugin interceptor="com.bi.dao.base.plugin.PagePlugin">
            <property name="dialect" value="mysql"/>
            <property name="pageSqlId" value=".*_page"/>
        </plugin>
    </plugins>

6、相关mapper.xml文件SQL
拿查询用户列表来举例:

    <sql id="userSort">
         <if test="pd.sortCond != null and pd.sortCond.size() != 0">
                order by
                <foreach collection="pd.sortCond" item="sortCond" separator=",">
                    ${sortCond.column} ${sortCond.order}
                </foreach>
         </if>  
    </sql>
    <select id="listAllUser_page" parameterType="Page" resultMap="userResultMap" useCache="false">
        select  u.USER_ID,
                u.USER_NAME,
                u.USER_PWD,
                u.USER_SEX,
                u.USER_ADDRESS,
                u.E_MAIL,
                u.USER_PHOTO,
                u.USER_PHONE,
                u.DEPT_ID,
                u.USER_STATUS,
                u.CREATE_BY,
                u.CREATE_TIME,
                u.LAST_LOGIN_TIME,
                u.SKIN 
        from BI_SYS_USER u
        where u.USER_NAME != 'admin'
        <if test="pd.userName != null and pd.userName != ''"><!-- 关键词检索 -->
            and u.USER_NAME LIKE CONCAT(CONCAT('%', #{pd.userName}),'%')
        </if>
        <if test="pd.userPhone != null and pd.userPhone != ''"><!-- 手机号码检索 -->
            and u.USER_PHONE=#{pd.userPhone} 
        </if>
        <if test="pd.deptId!=null and pd.deptId!=''"><!-- 部门检索 -->
            and u.DEPT_ID = #{pd.deptId} 
        </if>
        <if test="pd.userStatus!=null and pd.userStatus!=''"><!-- 用户状态检索 -->
            and u.USER_STATUS = #{pd.userStatus} 
        </if>
        <include refid="userSort"></include>
    </select>

7、controller类部分代码:

    @RequestMapping(value="/userSearch")
    @ResponseBody
    public Object userSearch(Page page){
        PageData pd = new PageData();
        pd = this.getPageData();
        page.setPd(pd);

        //调用封装方法,构造page参数
        page = DataTablesUtil.constructPd(page);
        //构造分页查询param------end------------
        //分页查询(查询SQL id必须以"_page"结尾)
        List<User>  userList = userService.listAllUser_page(page);

        //设置datatables要求返回的数据-----start-------
        /**
         * draw:请求次数计数器 要求原样返回
         * Data:查询结果List
         * recordsTotal:查询结果总数
         * recordsFiltered:过滤条件后的结果总数(一般与查询结果总数一致)
         */
        DataTables<User> dts = new DataTables();
        dts.setDraw(Integer.parseInt(pd.get("draw").toString()));
        dts.setData(userList);
        dts.setRecordsTotal(page.getTotalResult());
        dts.setRecordsFiltered(page.getTotalResult());
        //设置datatables要求返回的数据-----end-------

        return dts;
    }

8、补充一个DataTablesUtil.java
主要实现将前端传过来的参数处理后构造好Page类供查询service方法使用。

/**
 * 文件名: DataTablesUtil.java
 * 版    权: Copyright © 2013 - 2015 ThinkJF, Inc. All Rights Reserved
 * 描    述: <描述>
 * 创建人: Jeff
 * 创建时间: 2015年12月11日
 */
package com.bi.common.util;

import java.util.ArrayList;
import java.util.List;

import com.bi.common.base.entity.Page;
import com.bi.common.base.entity.SortCond;

/**
 * <p>
 * 功能描述:dataTables工具类
 * </p>
 * <p>
 * Company: 
 * </p>
 * 
 * @author Jeff
 * @version 1.0 2015年12月11日
 */
public class DataTablesUtil {

    /**
     * 构造Page类,包括设置startIndex,pageSize以及pd对象的查询参数及排序参数
     * @author Jeff
     * @version 1.0 2015年12月11日
     * @param page
     * @return
     */
    public static Page constructPd(Page page) {
        PageData pd = new PageData();
        pd = page.getPd();
        // 获取前端datatables参数---------start--------------
        // desc:draw,start,length
        // 计数器
        int draw = Integer.parseInt(pd.get("draw").toString());
        // 数据起始位置
        int startIndex = Integer.parseInt(pd.get("startIndex").toString());
        // 数据长度
        int pageSize = Integer.parseInt(pd.get("pageSize").toString());
        // 根据列索引获取该列列名
        String ColumnName = pd.getString("sortName");
        // 是降序还是升序
        String sortDir = pd.getString("sortDir");
        // 获取前端参数---------end--------------

        // 构造分页查询param------start------------
        // desc:pageSize,currentResult,sortCond
        page.setShowCount(pageSize);
        page.setCurrentResult(startIndex);
        // 排序设置
        if (ColumnName != null && !"".equals(ColumnName)) {
            List<SortCond> lsc = new ArrayList<SortCond>();
            SortCond sc = new SortCond(ColumnName,
                    "asc".equals(sortDir) ? SortCond.Order.ASC
                            : SortCond.Order.DESC);
            lsc.add(sc);
            pd.put("sortCond", lsc);
        }
        //将设置覆盖原pd
        page.setPd(pd);

        return page;
    }

}

二、前台bootstrap样式+datatable插件 数据渲染;
涉及到以下内容:
1、bootstrap与datatables相关css与js;
2、构造dataTables相关对象,设置相关参数;
3、html代码

1、css与js,可以直接上官网扒
dataTables.bootstrap.min.css
buttons.bootstrap.min.css
select.bootstrap.min.css
editor.bootstrap.min.css

jquery.dataTables.min.js
dataTables.bootstrap.min.js
dataTables.buttons.min.js
buttons.bootstrap.min.js
dataTables.select.min.js
dataTables.editor.min.js
editor.bootstrap.min.js

2、构造dataTables相关对象,设置相关参数

<script type="text/javascript">
//声明biUserManage对象
var biUserManage = {
    userTable : null,
    getQueryCondition : function(data) {
        var param = {};
        //处理datatables排序参数
        if (data.order&&data.order.length&&data.order[0]) {
            var indexColumn = data.order[0].column;
            param.sortName = data.columns[indexColumn].name;
            param.sortDir = data.order[0].dir;
        }
        //处理查询参数
        param.userName = $("#searchUserName").val();
        param.userPhone = $("#searchPhone").val();
        param.deptId = $("#searchDeptId").val();
        param.userStatus = $("#searchStatus").val();
        //处理分页参数
        param.startIndex = data.start;
        param.pageSize = data.length;
        param.draw = data.draw;
        return param;
    }
};

//初始化datatables 
$(function(){
    biUserManage.userTable =  $('#usertable').dataTable($.extend({
    //设置ajax数据源请求
    ajax: function(data, callback){
        //封装请求参数
        var param = biUserManage.getQueryCondition(data);
        $.ajax({
                type: "POST",
                url: "${rc.contextPath}/user/userSearch?systime=" + new Date().getTime(),
                data: param,
                dataType: "json",
                success: function(result) {                 
                    callback(result);                   
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("查询失败");
                    //$('#div-table-container').spinModal(false);
                }
            });
    },
    //默认按哪列排序
    order: [ 9, 'desc' ],
    //设置列相关信息
    columns: [//列定义参数
        CONSTANT.DATA_TABLES.CELL_CHECKBOX,
            {
                "data": "userId",
                "name": "USER_ID"
            },
            {
                "data": "userName",
                "name": "USER_NAME"
            },
            {
                "data" : "userSex",
                "name": "USER_SEX",
                "width" : "80px",
                "render" : function(data,type, row, meta) {
                    if(data==1){
                        return '<i class="fa fa-male"></i> 男';
                    }else{
                        return '<i class="fa fa-female"></i> 女';
                    }
                },
                "orderable" : false
            },
            {
                "data":"email",
                "name": "E_MAIL",
                "orderable" : false
            },
            {
                "data":"userPhone",
                "name": "USER_PHONE",
                "orderable" : false
            },
            {
                "data":"dept.deptName",
                "name": "DEPT_ID"
            },
            {
                "data": "userAddress",
                "name": "USER_ADDRESS",
                "orderable" : false
            },
            {
                "data" : "userStatus",
                "name": "USER_STATUS",
                "width" : "80px",
                "render" : function(data,type, row, meta) {
                    if(data==0){
                        return "注销";
                    }else if(data==1){
                        return "正常";
                    }else if(data==2){
                        return "暂停";
                    }
                }
            },
            {
                "data": "lastLoginTime",
                "name": "LAST_LOGIN_TIME",
                "width" : "120px"
            },
            {
                "data": null,
                "width" : "80px",
                "defaultContent":"",
                "orderable" : false
            }
    ],  
    //在最后一列增加编辑删除按钮             
    "createdRow": function ( row, data, index ) {
                        //行渲染回调,在这里可以对该行dom元素进行任何操作
                        $('td', row).eq(10).addClass("taC");
                        var btnEdit = $('<div class="userM-table-function"><a class="fa fa-pencil-square text-success"></a><div class="line"></div><a class="fa fa-trash text-danger"></a></div>');
                        $('td', row).eq(10).append(btnEdit);
                    }
    },CONSTANT.DATA_TABLES.DEFAULT_OPTION)).api();
});

//初始化其它 
$(function(){
    //加载搜索按钮点击事件
    $("#btnSearch").click(function(){
        biUserManage.isSearch = true;
        biUserManage.userTable.ajax.reload();
    });
});
/*常量*/
var CONSTANT = {
        DATA_TABLES : {
            DEFAULT_OPTION : { //DataTables初始化选项
                "language": {
                    "sProcessing":   "处理中...",
                    "sLengthMenu":   "每页 _MENU_ 项",
                    "sZeroRecords":  "没有匹配结果",
                    "sInfo":         "当前显示第 _START_ 至 _END_ 项,共 _TOTAL_ 项。",
                    "sInfoEmpty":    "当前显示第 0 至 0 项,共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix":  "",
                    "sSearch":       "搜索:",
                    "sUrl":          "",
                    "sEmptyTable":     "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands":  ",",
                    "oPaginate": {
                        "sFirst":    "首页",
                        "sPrevious": "上页",
                        "sNext":     "下页",
                        "sLast":     "末页",
                        "sJump":     "跳转"
                    },
                    "oAria": {
                        "sSortAscending":  ": 以升序排列此列",
                        "sSortDescending": ": 以降序排列此列"
                    }
                },
                "processing" : false,   //隐藏加载提示,自行处理
                "serverSide" : true,
                "searching"  : false,//禁用表格内搜索
                "lengthMenu" :[10,20,50,100]//定义页面长度组件里面的选项
            },
            CELL_CHECKBOX : {   //复选框单元格
                "className" : "cell-chechbox",
                "orderable" : false,
                "data": null,
                "width" : "40px",
                "render" : function(data, type, row, meta) {
                    return '<input type="checkbox" >';
                }
            }
        }
};      
</script>

3、html代码

<table class="table table-bordered table-hover " id="usertable">
                <thead>
                    <tr>
                        <th class="taC resource-content-check"><input type="checkbox"
                            class="check" id="allcheck" /></th>
                        <th class="taC cp" width="5%">编号</th>
                        <th class="taC cp" width="10%">姓名</th>
                        <th class="taC cp" width="5%">性别</th>
                        <th class="taC cp" width="10%">邮箱</th>
                        <th class="taC cp" width="10%">联系电话</th>
                        <th class="taC cp" width="10%">所属部门</th>
                        <th class="taC cp" width="15%">地址</th>
                        <th class="taC" width="5%">状态</th>
                        <th class="taC" width="18%">最后登录时间</th>
                        <th class="taC" width="10%">操作</th>
                    </tr>
                </thead>

            </table>

截止到这里,基本上整个代码都差不多贴完了,大家可以根据自己的项目实际情况进行修改;
这里可能还涉及一个前端与后台用json格式传递数据的问题,可以参照我关于这个问题的文章处理。
贴两个有关dataTables网站地址:
dataTables中文网:http://datatables.club/example/
dataTables参数说明:http://www.suchso.com/UIweb/jquery-DataTables-use-opertions-zhongwen-shuoming.html

 类似资料: