您的位置:首页 > Web前端 > BootStrap

使用Bootstrap-table实现ssm框架的分页Demo

2017-05-05 16:43 856 查看
    Bootstrap是一款很受欢迎的前端框架,在bootstrap的官网中提供了丰富的插件(http://www.bootcss.com/点击打开链接),根据bootstrap不同插件的API我们可以很方便的学习,今天我们来说一下Bootstrap-table(跟Bootstrap一样,对浏览器的要求稍微高点,IE8+、谷歌、Firefox。。。等浏览器)。

    Bootstrap-table,顾名思义,就是表格了,传统模式中我们手写table,想要达到一定的审美观,需要花费的功夫可以是一点两点,现在如果你的前端使用了bootstrap,那么Bootstrap-table表格将是你完美搭配的选择之一(还有datatable等插件可供我们选择)。

效果图:



我们先看一张代码全图(使用的是MyEclipse+MySQL+JDK 1.7+Tomcat7).







建立数据库:

/*
Navicat MySQL Data Transfer

Source Server         : 127.0.0.1_3306
Source Server Version : 50621
Source Host           : 127.0.0.1:3306
Source Database       : ssm

Target Server Type    : MYSQL
Target Server Version : 50621
File Encoding         : 65001

Date: 2017-05-05 16:22:04
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '10');
INSERT INTO `student` VALUES ('2', '李四', '15');
INSERT INTO `student` VALUES ('3', '小红', '8');
INSERT INTO `student` VALUES ('4', '小明', '20');
INSERT INTO `student` VALUES ('5', '诸葛亮', '30');
INSERT INTO `student` VALUES ('6', '周瑜', '20');
INSERT INTO `student` VALUES ('7', '孙悟空', '500');
INSERT INTO `student` VALUES ('8', '猪八戒', '200');
INSERT INTO `student` VALUES ('9', '唐僧', '20');
INSERT INTO `student` VALUES ('10', '阿尔法', '15');
INSERT INTO `student` VALUES ('11', '张学良', '12');
INSERT INTO `student` VALUES ('12', '小兰', '8');
INSERT INTO `student` VALUES ('13', '易烊千玺', '20');
INSERT INTO `student` VALUES ('14', '俞灏明', '30');
INSERT INTO `student` VALUES ('15', '游鸿明', '20');
INSERT INTO `student` VALUES ('16', '海明威', '28');
INSERT INTO `student` VALUES ('17', '毛主席', '10');
INSERT INTO `student` VALUES ('18', '哪咤', '8');
INSERT INTO `student` VALUES ('19', '红孩儿', '9');
INSERT INTO `student` VALUES ('20', '黄帝', '10');


关于实体类及mapper的映射文件,我们可以使用MyBatis-Generator这个插件来自动生成(在Config文件夹下面,不会的可以点击这里学习:点击打开链接)。在自动生成代码之前,我们需要在src下建立相应的包,不然会报错的

GeneratorConfig.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/pagination" userId="root"
password="root">
</jdbcConnection>

<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.voicecodes.pojo" targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.voicecodes.mapper" targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.voicecodes.mapper" targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>

<!-- 指定数据库表 -->
<table tableName="student" ></table>
</context>
</generatorConfiguration>


新建Generatorqlmap类来执行我们的generatorConfig.xml文件

package Generator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

public void generator() throws Exception{

List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File("config/Generator/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);

}
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}


然后,在项目中我们可以看到(StudentCustomMapper及StudentCustomMapper.xml是我自己新建的):



运行测试类之后,率先年项目出现上图就说明我们的自动生成代码成功,否则失败,请检查相关类

以上步骤结束后,正式开始代码类编写:

首先添加jar,所有的jar都在开始的图中了,在文章结尾我也会上传

db.properties是前提:

jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/ssm


顺便加上log4j.xml

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout


编写applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 【创建dao层所需要的对象】 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="5"/>
</bean>
<bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatisCfg.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.voicecodes.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlsessionFactory"></property>
</bean>

</beans>


springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<context:component-scan base-package="com.voicecodes"></context:component-scan>
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>

<!-- 静态资源的访问 -->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/plugs/**" location="/plugs/"/>

</beans>
mybatis.xml没有写实质性的内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration></configuration>


相关的配置文件就是这些。

接下来:

StudentCustomMapper

package com.voicecodes.mapper;

import com.voicecodes.pojo.Student;

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

public interface StudentCustomMapper {
List<Student> selectByFy(Map<String,Object> param);
}
StudentCustomMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.voicecodes.mapper.StudentCustomMapper" >
<select id="selectByFy" resultType="com.voicecodes.pojo.Student" parameterType="Map">
SELECT *
FROM student
<if test="a!=null">
<where>
<if test="name!=null and name!=''"> name=#{name}</if>
<if test="age!=null and age!=''">AND  age=#{age}</if>
</where>
LIMIT #{a},#{b}
</if>
</select>
</mapper>


StudentService
package com.voicecodes.service;

import java.util.Map;

public interface StudentService {
Map<String,Object> selectByFy(Map<String,Object> param);
}
StudentServiceImp

package com.voicecodes.service.imp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.voicecodes.mapper.StudentCustomMapper;
import com.voicecodes.pojo.Student;
import com.voicecodes.service.StudentService;

@Service
public class StudentServiceImp implements StudentService {
@Autowired
private StudentCustomMapper studentDao;

public Map<String,Object> selectByFy(Map<String, Object> param) {
//bootstrap-table要求服务器返回的json须包含:total,rows
Map<String,Object> result = new HashMap<String,Object>();
int total=studentDao.selectByFy(null).size();
List<Student> rows=studentDao.selectByFy(param);
result.put("total",total);
result.put("rows",rows);
return result;
}
}
StudentController

package com.voicecodes.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.voicecodes.service.StudentService;

@Controller
@RequestMapping("student")
public class StudentController {
@Autowired
private StudentService studentService;

@RequestMapping("selectByFy")
@ResponseBody
public  Map<String,Object> selectByFy(int pageSize,int pageNumber,String name,Integer age){
/*所需参数*/
Map<String, Object> param=new HashMap<String, Object>();
int a=(pageNumber-1)*pageSize;
int b=pageSize;
param.put("a", a);
param.put("b", b);
param.put("name", name);
param.put("age", age);
return studentService.selectByFy(param);
}
}


Jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta charset="utf-8">
<title>Bootstrap-Table</title>
<!-- jq -->
<script type="text/javascript" src="<%=basePath%>js/jquery-3.1.1.min.js"></script>

<!-- bootstrap -->
<link rel="stylesheet" href="<%=basePath%>/plugs/bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="<%=basePath%>/plugs/bootstrap/js/bootstrap.min.js"></script>

<!-- 分页插件 -->
<link rel="stylesheet" href="<%=basePath%>plugs/bootstrap-table/bootstrap-table.min.css">
<script type="text/javascript" src="<%=basePath%>plugs/bootstrap-table/bootstrap-table.min.js"></script>
<script type="text/javascript" src="<%=basePath%>plugs/bootstrap-table/bootstrap-table-locale-all.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:100px">
<div class="row">
<!-- 搜索框 -->
<div class="col-xs-6 pull-right">
<div class="input-group">
<input type="text" class=" form-control" name="age" placeholder="请输入年龄">
<input type="text" class=" form-control" name="name" placeholder="请输入姓名">
<span class="input-group-btn">
<button class="btn btn-default search" type="button">Go!</button>
</span>
</div>
</div>
<!-- 表格 -->
<div class="col-xs-12">
<table class="table table-striped table-bordered table-hover" ></table>
</div>
</div>
</div>
<script type="text/javascript">
class BstpTable{
constructor(obj) {
this.obj=obj;
}
inint(searchArgs){
//---先销毁表格 ---
this.obj.bootstrapTable('destroy');
//---初始化表格,动态从服务器加载数据---
this.obj.bootstrapTable({
//【发出请求的基础信息】
url: '<%=basePath%>student/selectByFy',
method: 'post',
contentType: "application/x-www-form-urlencoded",

//【查询设置】
/* queryParamsType的默认值为 'limit' ,在默认情况下 传给服务端的参数为:offset,limit,sort
设置为 ''  在这种情况下传给服务器的参数为:pageSize,pageNumber */
queryParamsType:'',
queryParams: function queryParams(params) {
var param = {
pageNumber: params.pageNumber,
pageSize: params.pageSize
};
for(var key in searchArgs){
param[key]=searchArgs[key]
}
return param;
},

//【其它设置】
locale:'zh-CN',//中文支持
pagination: true,//是否开启分页(*)
pageNumber:1,//初始化加载第一页,默认第一页
pageSize: 3,//每页的记录行数(*)
pageList: [2,3,4],//可供选择的每页的行数(*)
sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
showRefresh:true,//刷新按钮

//【样式设置】
height: 300,//table的高度
//按需求设置不同的样式:5个取值代表5中颜色['active', 'success', 'info', 'warning', 'danger'];
rowStyle: function (row, index) {
var style = "";
if (row.name=="小红") {style='success';}
return { classes: style }
},

//【设置列】
columns: [
{field: 'id',title: 'id'},
{field: 'name',title: '姓名'},
{field: 'age',title: '年龄'},
{field: 'tool',title: '操作', align: 'center',
formatter:function(value,row,index){
var element =
"<a class='edit' data-id='"+row.id +"'>编辑</a> "+
"<a class='delet' data-id='"+row.id +"'>删除</a> ";
return element;
}
}
]
})
}
}

var bstpTable=new BstpTable($("table"));
bstpTable.inint({})

$(".search").click(function(){
var searchArgs={
name:$("input[name='name']").val(),
age:$("input[name='age']").val()
}
bstpTable.inint(searchArgs)
})
</script>
</body>
</html>


关于导出和增删改暂时未做,后续会补上

源码下载:下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐