搞定BootstrapTable(后端使用SpringMVC+Hibernate)

还是那句老话,好记性不如烂笔头。记得以前的一个Demo项目里面有分页,但是没有用插件,自己手写的分页处理,但是效果并不是很好,最近接触到插件BootstrapTable,风格和Bootstrap统一,现在就来说说怎样使用它。

初上手,直接套json数据进去,然后设置分页方式为client',很快表格就做出来,但是一般项目中都是使用后台来进行分页的,不可能一下从数据库从捞出成千上万条数据,先不说流量的问题,客户端的渲染也吃力。在使用服务器后端分页的过程中,也遇到了一些问题,相信大部分初次接触BootstrapTable的人应该都会遇到。所以特此写一个完整的例子,后面应该还会继续完善,包括增、删、改。

好,废话少说,上代码。

先上项目架构:

项目使用maven构建,由于项目结构不是很复杂,所以就不做过多介绍。

接下来看index.jsp

<%@ page contentType="text/html;charset=UTF-8"%>
<html>
 
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-table.css" type="text/css">
<script type="text/javascript" src="js/jquery-2.0.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/bootstrap-table.js"></script>
<script type="text/javascript" src="js/bootstrap-table-zh-CN.js"></script>
 
<body>
    <p class="panel panel-default">
        <p class="panel-heading">
            <h3 class="panel-title text-center">Bootstrap-table样例演示</h3>
        </p>
        <p class="panel-body">
 
            <p id="toolbar" class="btn-group">
            <button id="btn_edit" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
        </p>
 
        <table data-toggle="table" id="table" data-height="400"
            data-classes="table table-hover" data-striped="true"
            data-pagination="true" data-side-pagination="server"
            data-search="true" data-show-refresh="true" data-show-toggle="true"
            data-show-columns="true" data-toolbar="#toolbar">
            <thead>
                <tr>
                    <th data-field="state" data-checkbox='ture'></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
        </table>
    </p>
    </p>
 
 
</body>
 
<script type="text/javascript">
    $("#superBtn").click(function() {
        $.get("getPageInfo?limit=5&offset=0", function(data, status) {
            alert(status);
            alert(data.userList[0].name);
        });
    });
     
    $(document).ready(function(){
        $("button[name='toggle']").height(20);
        $("button[name='refresh']").height(20);
    });
 
    function edit(id) {
        alert(id);
    }
 
    $("#table")
            .bootstrapTable(
                    {
                        url : "getPageInfo",    //数据请求路径
                        clickToSelect : true,  //点击表格项即可选择
                        dataType : "json",   //后端数据传递类型
                        pageSize : 5,
                        pageList : [ 5, 10, 20 ],
                    //  contentType : "application/x-www-form-urlencoded",
                        method : 'get',      //请求类型
                        dataField : "data",  //很重要,这是后端返回的实体数据!                 
                        //是否显示详细视图和列表视图的切换按钮
                        queryParams : function(params) {//自定义参数,这里的参数是传给后台的,我这是是分页用的  
                            return {//这里的params是table提供的  
                                offset : params.offset,//从数据库第几条记录开始  
                                limit : params.limit
                            //找多少条  
                            };
                        },
                        responseHandler : function(res) {
                            //在ajax获取到数据,渲染表格之前,修改数据源
                            return res;
                        },
                        columns : [
                                {
                                    field : 'state',
                                },
                                {
                                    field : 'id',
                                    title : 'ID',
                                    align : 'center'
                                },
                                {
                                    field : 'name',
                                    title : '姓名',
                                    align : 'center'
                                },
                                {
                                    field : 'age',
                                    title : '年龄',
                                    align : 'center'
                                },
                                {
                                    field : 'address',
                                    title : '地址',
                                    align : 'center'
                                },
                                {
                                    title : '操作',
                                    field : 'id',
                                    align : 'center',
                                    formatter : function(value, row, index) {
                                        var e = '<a href="#" mce_href="#" onclick="edit(\''
                                                + row.id + '\')">编辑</a> ';
                                        var d = '<a href="#" mce_href="#" onclick="del(\''
                                                + row.id + '\')">删除</a> ';
                                        return e + d;
                                    }
 
                                } ]
                    });
</script>
</html>
 

重要的几点:1、导入必要的css文件和js文件,并注意版本问题,这个后面会谈 2、queryParams:这是在点击分页或者初次加载表格的时候,前端向后端传递的数据,有2个,分别是limit和offset,limit表示请求的记录条数,offset表示记录的偏移量 3、dataField:表示后端传递的对象数据,名字要与对象的名字相同。

再来看Controller:

package controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import dao.UserDao;

@Controller
public class BootstrapTableController {

	@RequestMapping("/getPageInfo")
	public @ResponseBody Map getPageInfo(int limit,int offset) {
		System.out.println("limit is:"+limit);
		System.out.println("offset is:"+offset);
		UserDao userDao = new UserDao();
		Map map = userDao.queryPageInfo(limit, offset);
		return map;
	}
}

Controller接收前端传过来的limit和offset参数,然后根据这2个参数调用dao层方法来获取数据。再看UserDao:

package dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import entity.User;

public class UserDao {

	private Session session;

	private Transaction transaction;

	public Session getSession() {
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		return session;
	}

	public Map queryPageInfo(int limit, int offset) {
		String sql = "from User";
		Session session = this.getSession();

		Query query = session.createQuery(sql);
		query.setFirstResult(offset);
		query.setMaxResults(limit);
		List userList = query.list();

		String sql2 = "select count(*) from User";
		int totalRecord = Integer.parseInt(session.createQuery(sql2).uniqueResult().toString());

		Map map = new HashMap();
		map.put("total", totalRecord);
		map.put("data", userList);
		return map;
	}
}

userDao也是比较简单的,关键就是total和data了,这是要返回到前台的数据,注意名字要和前台相对应,你只要返回实体数据和记录总数就可以了,剩下的BootstrapTable替你搞定。

接下来在看看entity层的User

package entity;

public class User {

	private int id;
	
	private String name;
	
	private int age;
	
	private String address;

	public User() {
		super();
	}

	public User(int id,String name, int age, String address) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}

	public String getName() {
		return name;
	}	

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
	}
}

还有几个配置文件,分别是SpirngMVC的配置文件,还有web.xml以及pom.xml,该配的得配上:

SpringMVC-servlet.xml:





	
		
			
			
		
	

	
  
  	
    
    

    
    
        
        
    
  

web.xml:



	Archetype Created Web Application

	
		SpringMVC
		org.springframework.web.servlet.DispatcherServlet
		1
	
	
		SpringMVC
		/
	

	
		default
		*.css
	
	
		default
		*.js
	
	
        default
        *.ttf
    
    
        default
        *.woff
    
    
        default
        *.woff2
    



pom.xml:


	4.0.0
	Demo
	BootstrapDemo
	war
	0.0.1-SNAPSHOT
	BootstrapDemo Maven Webapp
	http://maven.apache.org
	
		
			junit
			junit
			3.8.1
			test
		
		
			javax.servlet
			javax.servlet-api
			3.1.0
			provided
		
		
			org.hibernate
			hibernate-core
			5.2.6.Final
		

		
			mysql
			mysql-connector-java
			5.1.41
		
		
		
			org.springframework
			spring-webmvc
			4.3.10.RELEASE
		
		
			com.fasterxml.jackson.core
			jackson-core
			2.8.9
		
		
			com.fasterxml.jackson.core
			jackson-databind
			2.8.9
		
			
			com.fasterxml.jackson.core
			jackson-annotations
			2.8.9
		
	
	
		BootstrapDemo
	


然后dao层的就算了,很简单。到这里基本上所有的关键都已经展示了,来看看效果吧:

不知道细心的你注意到没有,右上角的一个按钮明显大了一圈,这不太好,其实是它左边2个按钮小了一圈,在网上找了很久,基本上没有人遇到这样的问题,没办法,逼我出绝招,使用调试器跟踪这两个按钮元素,最后使用jQuery在表格加载完毕然后手动改变其大小,然后正常了。

当然,这只涉及到了查数据,还有数据的删除、新增和修改,后面再来介绍这些的实现,其实最关键的还是查,查做出来了,其他的就水到渠成了。