轻松玩转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在表格加载完毕然后手动改变其大小,然后正常了。
当然,这只涉及到了查数据,还有数据的删除、新增和修改,后面再来介绍这些的实现,其实最关键的还是查,查做出来了,其他的就水到渠成了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: MVC生成页码选择器返回HTML代码详解