第一步:引入必须的js文件和css文件,我的项目结构引入如下:
<link id="lay-tabs" href="${ctxStatic}/plugin/layui/dist/css/layui.css" rel="stylesheet" />
<script src="${ctxStatic}/plugin/layui/dist/layui.all.js"></script>
<script src="${ctxStatic}/plugin/layui/dist/layui.js"></script>
第二步:定义一个table,我采用js渲染,如下
<div class="col-lg-12">
<table id="waringDevicesTable" class="layui-hide"></table>
</div>
第三步:渲染的js代码
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="com.zy.modules.sys.utils.UserUtils" %>//引入包
<%
String adcd = UserUtils.getUser().getOffice().getArea().getId();//全局参数
%>
$(document).ready(function() {
// 表格初始化 -------------------------------------------------
var tableheight = document.documentElement.clientHeight - 330;
layui.use('table', function(){
var table = layui.table;//表格
//执行一个 table 实例
table.render({
elem: '#waringDevicesTable'
,height: tableheight
,text: {
none: '暂无相关数据' //默认:无数据。注:该属性为 layui 2.2.5 开始新增
}
,page: true //开启分页
,cols: [[
{field: 'name', title: '名称', width:180,align:'center'}
,{field: 'time', title: '时间', width:120,align:'center'}
,{field:'town',title: '所属乡镇', width:130,align:'center'}
,{field:'smallRiver',title: '所属小流域', width:210,align:'center'}
]]
,id: 'waringDevicesInfo'
,url:'${ctx}/ia/getHistoryMTDisasterOfTable?adcd='+"<%=adcd %>"//此adcd是我传入的参数
,limit:5//默认传入10
,limits:[5,10]//默认是[10]
});
});
});
第四步:后台server,我采用的是springmvc,此处不写controller,但是要注意controller的注解,
两个必须的注解:@ResponseBody定义返回后的数据直接转成json格式, @RequestMapping映射
public Map<String, Object> getHistoryMTDisasterOfTable(String adcd, HttpServletRequest request,
HttpServletResponse reponse) {
Map<String,String> param=new HashMap<>();//构建传入的参数,mybatis采用map传入参数
String limit=request.getParameter("limit");
int page=(Integer.parseInt(request.getParameter("page"))-1)*Integer.parseInt(limit);//计算分页
param.put("page", String.valueOf(page));
param.put("adcd", adcd);
param.put("limit", limit);
List<Map<String, Object>> listst = mapper.getHistoryMTDisasterOfTable(param);//mybatis返回的参数格式为map
Map<String,Object> resultMap=new HashMap<>();
//layui要求默认返回的数据格式就是这样,一个也不能少。
resultMap.put("code", 0);
resultMap.put("msg", "msg");
resultMap.put("count", mapper.getHistoryMTDisasterCount(param).get(0).get("count"));
resultMap.put("data", listst);
return resultMap;
}
第五步:mybatis的xml文件:此处不写了,大概说下,我传入的是map参数,返回也是map参数,
还是写一下吧。数据库是sqlserver,这里的分页用的是下面这句话:
ORDER BY h.ADDRESS OFFSET ${page} ROWS FETCH NEXT ${limit} ROWS ONLY
其中一个点mybatis中的$#的区别,一句话记住$是变量不会加单引号,而#是会加单引号的,
一般能用#就不要用$,防止sql注入。
<select id="getHistoryMTDisasterOfTable" resultType="map" parameterType="map">
SELECT
h.ADDRESS AS name,h.OTIME AS time,a.ADNM as town,w.WSNM as smallRiver
FROM IA_C_HSFWATER AS h
LEFT JOIN IA_Z_ADDT as a on a.ADCD=h.ADCD
LEFT JOIN IA_C_WATA as w on w.WSCD=h.WSCD
WHERE h.ADCD like #{adcd}+'%'
ORDER BY h.ADDRESS OFFSET ${page} ROWS FETCH NEXT ${limit} ROWS ONLY
</select>
第六步:注意:返回的数据格式是list套map格式:[{},{},{}],根据需求加工。