轻松玩转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> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title text-center">Bootstrap-table样例演示</h3> </div> <div class="panel-body"> <div 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> </div> <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> </div> </div> </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<String,Object> getPageInfo(int limit,int offset) { System.out.println("limit is:"+limit); System.out.println("offset is:"+offset); UserDao userDao = new UserDao(); Map<String,Object> 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<String, Object> 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<User> userList = query.list(); String sql2 = "select count(*) from User"; int totalRecord = Integer.parseInt(session.createQuery(sql2).uniqueResult().toString()); Map<String, Object> map = new HashMap<String, Object>(); 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:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- <mvc:annotation-driven/> --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </mvc:message-converters> </mvc:annotation-driven> <context:component-scan base-package="controller"/> <!-- 这两个类用来启动基于Spring MVC的注解功能,将控制器与方法映射加入到容器中 --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 这个类用于Spring MVC视图解析 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff2</url-pattern> </servlet-mapping> </web-app>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Demo</groupId> <artifactId>BootstrapDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>BootstrapDemo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.6.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.9</version> </dependency> </dependencies> <build> <finalName>BootstrapDemo</finalName> </build> </project>
然后dao层的就算了,很简单。到这里基本上所有的关键都已经展示了,来看看效果吧:
不知道细心的你注意到没有,右上角的一个按钮明显大了一圈,这不太好,其实是它左边2个按钮小了一圈,在网上找了很久,基本上没有人遇到这样的问题,没办法,逼我出绝招,使用调试器跟踪这两个按钮元素,最后使用jQuery在表格加载完毕然后手动改变其大小,然后正常了。
当然,这只涉及到了查数据,还有数据的删除、新增和修改,后面再来介绍这些的实现,其实最关键的还是查,查做出来了,其他的就水到渠成了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。