bootstrap实现分页

本文详细介绍如何使用Bootstrap和Bootstrap-table插件构建动态表格,包括下载、引入文件、编写HTML结构及JavaScript配置,最后展示了完整的实现效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.官网下载bootstrap,bootstrap-table

https://v3.bootcss.com/

http://bootstrap-table.wenzhixin.net.cn/

2.引入css和js

  此处引用的是themeleaf写法
	<link th:href="@{/bootstrap/css/bootstrap.css}" rel="stylesheet">
    <link th:href="@{/bootstrap/css/bootstrap-table.css}" rel="stylesheet">
    <script th:src="@{/jquery/jquery-1.11.1.min.js}" ></script>
    <script th:src="@{/bootstrap/js/bootstrap.js}" ></script>
    <script th:src="@{/bootstrap/js/bootstrap-table.js}" ></script>

3.html代码

<div id="content">
       <table id="table"></table>
       <div id="toolbar" class="btn-group">
           <button id="btn_add" type="button" class="btn btn-danger" data-toggle="modal" data-target="#addModal">
               <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>修改用户信息
           </button>
           <button id="btn_delete" type="button" class="btn btn-info">
               <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除用户信息
           </button>
       </div>
       </table>
</div>

4.script

<script>
	$(function(){
		$('#table').bootstrapTable({
            url: '',
            method: 'post',
            contentType:"application/x-www-form-urlencoded",//method为post时必须加上这个,否则接收不到参数
            dataType: 'json',
            queryParams:function queryParams(params) {   //设置查询参数

                var param = {

                    pageSize: params.limit,   //每页多少条数据
                    pageNumber: params.offset, //从第几条数据开始
                    searchText: params.search  //搜索框
                };
                //alert("pageSize="+params.limit+"pageNumber="+params.offset+"searchText="+searchText);
                return param;
            },
            height: 560,
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页(*)
            maintainSelected: true,             //设置为 true 在点击分页按钮或搜索按钮时,将记住checkbox的选择项
            sidePagination: "server",          //分页方式:client客户端分页,server服务端分页(*)
            pageNumber: 1,                       //初始化加载第一页,默认第一页
            pageSize: 10,                       //每页的记录行数(*)
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数(*)
            search: true,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
            strictSearch: true,                //设置为 true启用 全匹配搜索,否则为模糊搜索
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "userid",                  //每一行的唯一标识,一般为主键列\
            sortStable: true,
            columns: [
                {checkbox: true},
                {field: 'userid', title: 'ID'},
                {field: 'username', title: '姓名'},
                {field: 'userno', title: '用户编号'},
                {field: 'login', title: '登录名'},
                {field: 'pw', title: '密码'},
                {field: 'sex', title: '性别'},
                {field: 'birthday', title: '出生年月',
                    formatter: function (row,index,value) {
                        if (value != null) {
                            var date = new Date(value);
                            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                        }
                    }},
                {field: 'telephone', title: '联系电话'},
                {field: 'idcard', title: '身份证号'},
                {field: 'email', title: '邮箱'}
            ]
        });
	});
</script>

5.controller部分代码

@RequestMapping("/queryAll")
    @ResponseBody
    public String queryAll(Integer pageSize, Integer pageNumber, String searchText, HttpServletRequest request,
                           HttpServletResponse response) throws  Exception{
        //搜索框功能
        if (null != searchText) {
            searchText = "'%"+searchText+"%'";//sqlserver模糊查询
        }else{
            searchText = "'%"+""+"%'";//sqlserver模糊查询
        }
        //在service通过条件查询获取指定页的数据的list
        List<User> list = userService.queryAll(pageSize, pageNumber, searchText);
        System.out.println(list.size());
        //根据查询条件,获取符合查询条件的数据总量
        Integer total = userService.pageCount(searchText);
        //System.out.println(total);
        //自己封装的数据返回类型,bootstrap-table要求服务器返回的json数据必须包含:totlal,rows两个节点(sidePagination: "server"服务端分页)
        Map<String, Object> maps = new HashMap<>();
        maps.put("rows",list);
        maps.put("total",total);
        //System.out.println(maps.size());
        return mapToJson(maps);

6.mapper

//sqlserver分页查询注解方式,由于采用#{}取值方式,默认为变量添加单引号导致语句保错,此处采用${}取值方式
 @Select("select top ${pageSize} * from user_info where userid not in (select top ${pageNumber} userid from user_info) " +
            "and (username like ${searchText} or login like ${searchText} )")
    public List<User> queryAll(@Param("pageSize") Integer pageSize,@Param("pageNumber") Integer pageNumber,@Param("searchText") String searchText);

    @Select("select count(1) from user_info where username like ${searchText} or login like ${searchText}")
    @ResultType(Integer.class)
    public Integer queryCount(@Param("searchText") String searchText);

7.效果图

package com.org.controller; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.org.BaseController; import com.org.model.User; import com.org.service.IUserService; /** * @Author:liangjilong * @Date:2014-2-25 * @Version:1.0 * @Description: */ @Controller public class UserController extends BaseController { @Resource private IUserService userService; /*** * 方法一请求使用String * * 请求@RequestMapping匹配的URL request * * @param response * @return * @throws Exception */ @RequestMapping(value = "/userList1.do") public String userList1(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); List<User> lists = userService.getUserList(); if (lists != null) { request.setAttribute("userList", lists); } // userList指跳转到userList.jsp页面 return "userList"; } /** * 方法二请求使用ModelAndView * * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/userList2.do") public ModelAndView userList2(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); List<User> lists = userService.getUserList(); if (lists != null) { request.setAttribute("userList", lists); } // userList指跳转到userList.jsp页面 return new ModelAndView("userList"); } /*** * 自定义标签实现分页 * * @param request * @param response * @param @ResponseBody ajax响应 * @param method={RequestMethod.POST,RequestMethod.GET}表单请求 * @param consumes="application/json; charset=UTF-8"请求格式是json * @return * @throws UnsupportedEncodingException * @throws Exception */ @RequestMapping(value = "/pageList.do" ,method={RequestMethod.POST,RequestMethod.GET}) public @ResponseBody ModelAndView getUserInfo(Model model, @RequestParam(required = false) String username, @RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize) { try { String userName = new String(username.getBytes("ISO-8859-1"),"UTF-8");//处理乱码 Map<String, Object> map = new HashMap<String, Object>(); username=(username==null)?"":username; map.put("username", username);//username必须要和ibatis配置的property=username一致 Integer totalCount = this.userService.getUserCount(map); this.initPage(map, pageNum, pageSize, totalCount); List list = this.userService.getUserLists(map); this.initResult(model, list, map); return new ModelAndView("pagerList"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 添加用户 * @param type * @param model * @return */ @RequestMapping("/addUser.do") public ModelAndView addUser(@RequestParam String username, Model model) { User user = new User(); user.setUsername(username); this.userService.addUser(user); return this.getUserInfo(model, null, null, null); } /*** * 删除用户 * @param id * @param pageNum * @param pageSize * @param model * @return */ @RequestMapping(value="/delUser.do",method={RequestMethod.POST,RequestMethod.GET},consumes="application/json; charset=UTF-8") @ResponseBody public ModelAndView delUser(@RequestParam(required = true) Integer id, @RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize, Model model, HttpServletRequest request,HttpServletResponse response) { PrintWriter out=null; JSONObject result=new JSONObject(); try { out=response.getWriter(); this.userService.delUserById(id); result.put("flag", true); out.write(result.toString()); } catch (Exception e) { try { result.put("flag", false); out.write(result.toString()); } catch (JSONException e1) { e1.printStackTrace(); } } return null; //return this.getUserInfo(model, null, pageNum, pageSize); } /*** * 编辑用户 * @param id * @param model * @return */ @RequestMapping("/getUserById.do") public ModelAndView getUserById(@RequestParam(required = true) Integer id, Model model) { User u = this.userService.getUserById(id); model.addAttribute("user", u); return new ModelAndView("editUser"); } /*** * 编辑用户 * @param id * @param model * @return */ @RequestMapping("/editUser.do") public ModelAndView editUser(@RequestParam(required = true) Integer id, @RequestParam String username, @RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize, Model model) { User u = new User(); u.setUsername(username); this.userService.editUser(u); return this.getUserInfo(model, null, pageNum, pageNum); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值