欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

datatables+springmvc+bootstrap实现分页

程序员文章站 2022-04-29 17:45:44
...

  datatables是前端的一个实现分页的插件,支持主流的浏览器,非常好用。datatables网址:http://www.datatables.club/

里面有许多的样式,还支持bootstrap。这里用datatables+springmvc+bootstrap做了一个样例。

  效果图:

datatables+springmvc+bootstrap实现分页

数据是从服务器获取的,因为数据库不大,所有数据都通过json全部都传到前台了,datatables获取到数据就可以实现自动分页。

datatables使用

前台页面引入需要的js,css,然后添加一个table,表头自己定义

 <!--第一步:引入Javascript / CSS (CDN)-->  
    <!-- DataTables CSS -->  
    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.15/css/jquery.dataTables.css">  
       
    <!-- jQuery -->  
    <script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>  
       
    <!-- DataTables -->  
    <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>  
   .......................................................................................................................  
               <!-- 显示表格边框table-bordered  缩小表格间距table-condensed -->  
        <table id="example" class="table table-bordered table-condensed">  
            <thead>  
                <tr>  
                    <th><input type="checkbox" name="allChecked" /></th>  
                    <th>id</th>  
                    <th>学号</th>  
                    <th>姓名</th>  
                    <th>章节得分</th>  
                    <th>oj习题得分</th>  
                    <th>智能达标测试得分</th>  
                    <th>总得分</th>  
                    <th>操作</th>  
                </tr>  
            </thead>  
        </table>  

 

js使用:

$(function() {  
      
       
    var table = $("#example").DataTable({  
        "aLengthMenu":[10,20,40,60],//每页显示的条数,下拉框  
        "searching":true,//禁用搜索  
        "lengthChange":true,  
        "paging": true,//开启表格分页  
        "bProcessing" : true,//翻页时显示正在加载中  
        //"bServerSide" : true,//服务端模式  
        "bAutoWidth" : false,//是否自动适应宽度  
        "sort" : "position",//禁用排序  
        "deferRender":true,//延迟渲染   
        "bStateSave" : true, //在其他页面刷新,会自动到第一页  
        "length" : 10,//每页显示的条数  
        "start" : 0,  
        "dom": '<l<\'#topPlugin\'>f>rt<ip><"clear">',  
        "ordering": false,//全局禁用排序  
        "ajax": {  
                "type": "POST",  
                "url":contextPath + "/showZhangScoreService",  
                //查询传的参数  
                /*"data":function(d){  
                    d.state=$("#state").val();  
                    d.deptname=$("#deptname").val().trim();  
                    d.startTime=$("#startTime").val();  
                    d.endTime=$("#endTime").val();  
                }*/  
        },  
        "aoColumns" : [{  
            //指的是类里面的id,存放  
            "mData" : "runId",//类里面对应的属性  
            "orderable": false , // 禁用排序  
            "sDefaultContent" : "",//默认值  
            "sWidth" : "2%"//列的宽度  
                },{  
                    //指的是类里面的id,存放   
                    "mData" : "runId",//类里面对应的属性  
                    "orderable": false , // 禁用排序  
                    "sDefaultContent" : "",//默认值  
                    "sWidth" : "5%"//列的宽度  
                },   
                {  
                    "mData" : "userId",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : "",  
                    "sWidth" : "10%"  
                }, {  
                    "mData" : "userName",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : "",  
                    "sWidth" : "10%"  
                },  
                {  
                    "mData" : "frist",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : "",  
                    "sWidth" : "10%"  
                },  
                {  
                    "mData" : "second",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : '',  
                    "sWidth" : "10%"  
                      
                },  
                {  
                    "mData" : "thrid",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : "",  
                    "sWidth" : "10%"  
                },  
                {  
                    "mData" : "total",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : '',  
                    "sWidth" : "10%"  
                      
                },  
                {  
                    "mData" : "runId",  
                    "orderable" : false, // 禁用排序  
                    "sDefaultContent" : '',  
                    "sWidth" : "10%",  
                    "render":function(data, type, full, meta){  
                    return  data='<button id="deleteOne" class="btn btn-danger btn-sm" data-id='+data+'>删 除</button>';  
                          
                    }     
                }],  

 

如果数据库比较大的话是要开启"bServerSide" : true,//服务端模式,这样可以根据传入的参数去数据库取数据,本案例是取所有的数据,所以没有开启服务器模式。

没有开启服务器模式的请求参数,在开发者模式可以看到参数是比较少的。

datatables+springmvc+bootstrap实现分页

开启服务器模式后参数会变多,有start和length这两个参数,start表示开始取数据的位置,length表示取的数量,后端接收到这两个参数,就可以根据这个来查询。

datatables+springmvc+bootstrap实现分页

springmvc返回json数据

@Autowired  
private ZhangScoreService zhangScoreService;  
  
@RequestMapping("/showZhangScoreService")  
@ResponseBody  
public Map<String, Object> showZhangScoreService() throws Exception {  
    List<ZhangScore> ZhangScorelist = zhangScoreService.selsectAllZhangScore();  
    System.out.println(ZhangScorelist.size());  
    ZhangScore zhangScore= zhangScoreService.selectByPrimaryKey(29);  
    System.out.println(zhangScore.toString());  
    Map<String, Object> map2Json = new HashMap<String, Object>();  
    map2Json.put("aaData", ZhangScorelist);  
    return map2Json;  
}  

 

 

springmvc导出csv表格的RequestMapper

@RequestMapping("/export")  
public void exportcsv(HttpServletRequest request,HttpServletResponse response) throws Exception{  
     SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
     List exportData = new ArrayList<Map>();  
    List<ZhangScore> list=  zhangScoreService.selsectAllZhangScore();  
    if(list!=null){  
        for (ZhangScore d:list) {  
             Map<String, String> row = new LinkedHashMap<String, String>();  
             row.put("1", d.getUserId());  
             row.put("2", d.getUserName());  
             row.put("3", d.getFrist()+"");  
             row.put("4", d.getSecond()+"");  
             row.put("5", d.getThrid()+"");  
             row.put("6", d.getTotal()+"");  
             exportData.add(row);  
        }  
           LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();  
            map.put("1", "学号");  
            map.put("2", "姓名");  
            map.put("3", "章节得分");  
            map.put("4", "oj习题得分");  
            map.put("5", "智能达标测试得分");  
            String fileName=String.valueOf("信息"+new Date().getTime());  
            try {  
                response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8")+".csv");  
                response.setContentType("application/csv");  
                //response.setContentType("application/x-msdownload");  txt  
                response.setCharacterEncoding("UTF-8");  
                  
                String agent = request.getHeader("User-Agent");  
                boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);  
                if( isMSIE ){  
                    fileName = URLEncoder.encode(fileName,"UTF8");  
                }else{  
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");  
                }  
                //response.addHeader("Content-Length", "" + file.length());  
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开  
               // response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");  
                  ExportCsvUtil.createCSVFile(exportData, map, response.getOutputStream());  
              //  ExportCsvUtil.createTxtFile("6901285991219\t1\r\n6928防护等级459\t1",response.getOutputStream());  
  
            } catch (IOException e) {  
                e.printStackTrace();  
  
            }  
    } 

 

创建csv类

public class ExportCsvUtil {
	public static File createCSVFile(List exportData, LinkedHashMap rowMapper,
			OutputStream out) {

		File csvFile = null;
		BufferedWriter csvFileOutputStream = null;
		try {

			// GB2312使正确读取分隔符","
			csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
					out, "GB2312"), 1024 * 100);
			// 写入文件头部
			for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
					.hasNext();) {
				Entry propertyEntry = (Entry) propertyIterator.next();
				csvFileOutputStream.write("\""
						+ propertyEntry.getValue().toString() + "\"");
				if (propertyIterator.hasNext()) {
					csvFileOutputStream.write(",");
				}
			}
			csvFileOutputStream.newLine();

			// 写入文件内容
			for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
				// Object row = (Object) iterator.next();
				LinkedHashMap row = (LinkedHashMap) iterator.next();
				System.out.println(row);

				for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator
						.hasNext();) {
					Entry propertyEntry = (Entry) propertyIterator.next();
					// System.out.println( BeanUtils.getProperty(row,
					// propertyEntry.getKey().toString()));
					csvFileOutputStream.write("\""
							+ propertyEntry.getValue().toString() + "\"");
					if (propertyIterator.hasNext()) {
						csvFileOutputStream.write(",");
					}
				}
				if (iterator.hasNext()) {
					csvFileOutputStream.newLine();
				}
			}
			csvFileOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				csvFileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return csvFile;
	}

 

 

 

datatables+springmvc+bootstrap实现分页

前台通过js获取到选中的id,通过ajax就可以实现批量删除的功能。

datatables+springmvc+bootstrap实现分页

本案例下载地址:https://download.csdn.net/download/bushqiang/10393004