layui學習crud

Layui_1.0.9_分頁實例_Java

https://www.cnblogs.com/eRrsr/p/8367749.html

一、實體

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

package com.ebd.application.modules.taskManage.pojo;

 

import com.ebd.application.common.Base.BaseBean;

 

public class Task extends BaseBean{

 

    private String tName;   //任務名稱

    private String tStatus; //任務狀態(0:未執行;1:執行成功;2執行失敗)

    private String tSchedule;   //任務進度

    private String tDesc;   //任務簡述

    private String tDatasource;

     

    public String gettName() {

        return tName;

    }

    public void settName(String tName) {

        this.tName = tName;

    }

    public String gettStatus() {

        return tStatus;

    }

    public void settStatus(String tStatus) {

        this.tStatus = tStatus;

    }

    public String gettSchedule() {

        return tSchedule;

    }

    public void settSchedule(String tSchedule) {

        this.tSchedule = tSchedule;

    }

    public String gettDesc() {

        return tDesc;

    }

    public void settDesc(String tDesc) {

        this.tDesc = tDesc;

    }

    public String gettDatasource() {

        return tDatasource;

    }

    public void settDatasource(String tDatasource) {

        this.tDatasource = tDatasource;

    }

}

二、前端頁面

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<meta http-equiv="Access-Control-Allow-Origin" content="*">

<meta name="renderer" content="webkit">

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<meta name="apple-mobile-web-app-status-bar-style" content="black">

<meta name="apple-mobile-web-app-capable" content="yes">

<meta name="format-detection" content="telephone=no">

<%

    String path = request.getContextPath();

    String rootPath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + "/";

    String basePath = request.getScheme() + "://"

            + request.getServerName() + ":" + request.getServerPort()

            + path;

    request.setAttribute("basePath", basePath);

    request.setAttribute("rootPath", rootPath);

    pageContext.setAttribute("newLineChar", "\n");

%>

<link rel="stylesheet" href="${basePath}/static/layui/css/layui.css" media="all" />

<link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" />

<link rel="stylesheet" href="${basePath}/static/css/tasks.css" media="all" />

</head>

<body class="childrenBody">

    <blockquote class="layui-elem-quote tasks_search layui-form">

        <input id="checkids" type="hidden">

        <div class="layui-inline">

            <div class="layui-input-inline">

                <input type="text" placeholder="請輸入關鍵字" class="layui-input search_input">

            </div>

            <div class="layui-input-inline">

                <select lay-verify="required" class="search_select">

                  <option value="">請選擇任務狀態</option>

                  <option value="0">未執行</option>

                  <option value="1">執行成功</option>

                  <option value="2">執行失敗</option>

                </select>

              </div>

            <a class="layui-btn search_btn" id="search">查詢</a>

        </div>

        <div class="layui-inline">

            <a class="layui-btn layui-btn-normal tasksAdd_btn" style="background-color:#5FB878">添加任務</a>

        </div>

        <div class="layui-inline">

            <a class="layui-btn tasksEdit_btn">編輯任務</a>

        </div>

        <div class="layui-inline">

            <a class="layui-btn layui-btn-warm tasksDel_btn">選擇刪除</a>

        </div>

        <div class="layui-inline">

            <a class="layui-btn layui-btn-danger tasksBatchDel_btn">批量刪除</a>

        </div>

    </blockquote>

    <div class="layui-form tasks_list">

        <table class="layui-table">

            <colgroup>

                <col width="50">

                <col width="10%">

                <col>

                <col width="7%">

                <col width="25%">

                <col width="8%">

                <col width="15%">

                <col width="15%">

            </colgroup>

            <thead>

                <tr>

                    <th><input type="checkbox" lay-skin="primary" lay-filter="allChoose" id="allChoose"></th>

                    <th>名稱</th>

                    <th>簡述</th>

                    <th>狀態</th>

                    <th>進度</th>

                    <th>創建者</th>

                    <th>創建時間</th>

                    <th>操作</th>

                </tr>

            </thead>

            <tbody class="tasks_content" ></tbody>

        </table>

    </div>

    <div id="page"></div>

    <script type="text/javascript" src="${basePath}/static/js/jquery.js"></script>

    <script type="text/javascript" src="${basePath}/static/layui/layui.js"></script>

    <script type="text/javascript">

        $(function(){

              //初始化列表及分頁

              submit();

              //點擊查詢時觸發

              $("#search").click(function(){

                //當點擊搜索的時候,起始搜索值爲0-10,且當前頁回到第一頁

                startPage = 0;

                currentPage = 1;

                submit();

              })

        });

 

        //分頁參數設置 這些全局變量關係到分頁的功能

        var startPage = 0;

        var limitNum = 10;

        var currentPage = 1;

        var totalPage = 0;

        //ajax請求後臺數據

        function submit(){

            var selectName = $(".search_input").val()

            var selectStatus = $(".search_select").val()

            $.ajax({

                type:"post",

                async:false,

                url:"${basePath}/task/taskListByPage.htm",

                data:{start:startPage, limit:limitNum,selectName:selectName,selectStatus:selectStatus},

                success:function(data,status){

                    data=eval("("+data+")"); //轉爲對象

                    startPage = data.currentIndex;//當前頁數(後臺返回)

                    totalPage = data.totalPage;//總頁數(後臺返回)

                    toPage(data.dataList);

                }

            });

        }

 

        //看看參數有的是否爲空(data:後臺數據)

        function toPage(data){

            layui.use(['form', 'layer', 'layedit', 'laydate', 'laypage', 'element'], function() {

                var form = layui.form(),

                layer = layui.layer,

                layedit = layui.layedit,

                laydate = layui.laydate,

                laypage = layui.laypage,

                element = layui.element();

                //調用分頁

                laypage({

                    cont: 'page'

                    ,pages: totalPage

                    ,curr: currentPage

                    ,skip: true

                    ,jump: function(obj, first){

                        currentPage = obj.curr;

                        startPage = (obj.curr-1)*limitNum;

                        getBacktasks(data); //渲染數據

                        if(!first){ //加此判斷,避免初始時會無限刷新

                          submit(); //一定要把翻頁的ajax請求放到這裏,不然會請求兩次。

                        }

                        element.init();

                        form.render();

                    }

                  });

                //全選

                form.on('checkbox(allChoose)', function (data) {

                    var checkvals="";

                    var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');

                    child.each(function (index, item) {

                        item.checked = data.elem.checked;

                        if(item.checked){

                            checkvals += ","+item.value;

                        }

                    });

                    //捕捉被選記錄個數及id

                    $("#checkids").attr("valength",checkvals.split(",").length-1);

                    $("#checkids").val(checkvals);

                    form.render('checkbox');

                });

               //通過判斷文章是否全部選中來確定全選按鈕是否選中

               form.on("checkbox(choose)", function (data) {

                    var checkvals="";

                    var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');

                    var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')

                    if (childChecked.length == child.length) {

                        $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;

                    } else {

                        $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;

                    }

                    //遍歷被選中的記錄

                    for(var i=0;i<childChecked.length;i++){

                        checkvals += ","+childChecked[i].value;

                    }

                    //捕捉被選記錄個數及id

                    $("#checkids").attr("valength",childChecked.length);

                    $("#checkids").val(checkvals);

                    form.render('checkbox');

                })

                 

                //處理進度條(n:後臺獲取;timer:循環index;id:任務id;start:點擊啓動時記錄任務對象)

                var n = 0, timer = 0, id, start;

                var DISABLED = 'layui-btn-disabled';

                var active = {

                    loading: function(othis){

                      start = othis;

                      if(othis.hasClass(DISABLED)) return;

                      //初始化n

                      n = parseInt(othis.context.lang);

                      //loading

                      timer = setInterval(function(){

                        n = n + Math.random()*10|0

                        if(n>100){

                          n = 100;

                          clearInterval(timer);

                          othis.removeClass(DISABLED);

                          //記錄到數據庫

                          taskSchedule(100,othis.context.name);

                        }

                        element.progress(othis.context.id, n+'%');

                      }, 300+Math.random()*1000);

                      othis.addClass(DISABLED);

                    },stop: function(othis){

                        //記錄進度

                        start.context.lang = n;

                        //停止循環

                        clearInterval(timer);

                        //去除disabled標記

                        start.removeClass(DISABLED);

                        //記錄到數據庫

                        taskSchedule(n,othis.context.name);

                    }

                  };

                   

                  $('.taskProgress').on('click', function(){

                    var othis = $(this), type = $(this).data('type');

                    active[type] ? active[type].call(this, othis) : '';

                  });

            });

        };

         

        //遍歷裝載數據

        function getBacktasks(data){

            var htmlStr = "";

            $.each(data,function(v,o){

                htmlStr+="<tr><td><input type=\"checkbox\" lay-skin=\"primary\" class='cd_checkbox' value=\""+o.id+"\" lay-filter=\"choose\"></td>";

                htmlStr+='<td>'+o.tName+'</td>';

                htmlStr+='<td>'+o.tDesc+'</td>';

                htmlStr+='<td>';

                if(0==o.tStatus){

                    htmlStr+='<i class=\"layui-icon\" style=\"font-size: 30px; color: #FFB800;\"></i>'

                }else if(1==o.tStatus){

                    htmlStr+='<i class=\"layui-icon\" style=\"font-size: 30px; color: #5FB878\"></i>'

                }else{

                    htmlStr+='<i class=\"layui-icon\" style=\"font-size: 30px; color: #FF5722;\">ဆ</i>'

                }

                htmlStr+='</td>';

                htmlStr+='<td>';

                htmlStr+='<div class=\"layui-progress layui-progress-big\" lay-showpercent=\"true\" lay-filter=\"task_'+o.id+'\">';

                htmlStr+='  <div class=\"layui-progress-bar layui-bg-green\" lay-percent=\"'+o.tSchedule+'%\"></div>';

                htmlStr+='</div>';

                htmlStr+='</td>';

                htmlStr+='<td>'+o.creater+'</td>';

                htmlStr+='<td>'+o.createDate+'</td>';

                htmlStr+='<td>';

                htmlStr+='<a class=\"layui-btn layui-btn-mini taskProgress\" data-type=\"loading\" id=\"task_'+o.id+'\" name=\"'+o.id+'\" lang=\"'+o.tSchedule+'\"><i class=\"iconfont icon-edit\"></i>啓動</a>';

                htmlStr+='<a class=\"layui-btn layui-btn-danger layui-btn-mini taskProgress\" data-type=\"stop\" name=\"'+o.id+'\"><i class=\"layui-icon\"></i>停止</a>';

                htmlStr+='</td></tr>';

            });

 

            if(data.length>0){

                $("#page").show();

                $(".tasks_content").html(htmlStr);

            }else{

                $("#page").hide();

                $(".tasks_content").html("<tr><td colspan='9'>暫無數據</td></tr>");

            }

             

            //清空checkids(checkbox記錄)

            $("#checkids").attr("valength",0);

            $("#checkids").val("");

        }

         

       //=============================點擊事件===============================

       $(window).one("resize",function(){

            $(".tasksAdd_btn").click(function(){

                var index = layui.layer.open({

                    title : "添加任務",

                    type : 2, anim: 2,

                    content : "${basePath}/task/modifyPage.htm",

                    success : function(layero, index){

                        setTimeout(function(){

                            layui.layer.tips('點擊此處返回數據源列表', '.layui-layer-setwin .layui-layer-close', {

                                tips: 3

                            });

                        },500)

                    }

                })         

                 

                layui.layer.full(index);

            });

            $(".tasksEdit_btn").click(function(){

                if($("#checkids").attr("valength")==1){

                    task_edit($("#checkids").val().substring(1));

                }else{

                    layui.layer.alert('友情提示:請選擇一條記錄進行編輯', {

                      skin: 'layui-layer-molv'

                      ,closeBtn: 0

                    });

                }

            });

            $(".tasksDel_btn").click(function(){

                if($("#checkids").attr("valength")==1){

                    task_del($("#checkids").val().substring(1));

                }else{

                    layui.layer.alert('友情提示:請選擇一條記錄進行刪除', {

                      skin: 'layui-layer-molv'

                      ,closeBtn: 0

                    });

                }

            });

            $(".tasksBatchDel_btn").click(function(){

                if($("#checkids").attr("valength")>=1){

                    task_del($("#checkids").val().substring(1));

                }else{

                    layui.layer.alert('友情提示:至少選擇一條記錄進行刪除', {

                      skin: 'layui-layer-molv'

                      ,closeBtn: 0

                    });

                }

            });

        }).resize();

        function task_edit(id){

           var index = layui.layer.open({

                title : "編輯任務",

                type : 2, anim: 2,

                content : "${basePath}/task/modifyPage.htm?id="+id,

                success : function(layero, index){

                    setTimeout(function(){

                        layui.layer.tips('點擊此處返回數據源列表', '.layui-layer-setwin .layui-layer-close', {

                            tips: 3

                        });

                    },500)

                }

            })         

            layui.layer.full(index);

        }

        function task_del(ids){

            layer.confirm('友情提示:你確定要刪除該記錄嗎', {skin: 'layui-layer-molv' }, function(index){

                $.ajax({

                    type : "POST",

                    async : false,

                    dataType : "JSON",

                    cache : false,

                    url : "${basePath}/task/delete.htm",

                    data :  {"ids":ids},

                    success : function(data) {

                        if (data.flag) {

                            layer.msg(data.msg, {

                              icon:data.msgIcon,

                              time:data.msgTime

                            }, function(){

                                submit();

                            }); 

                        } else {

                            layer.msg(data.msg, {

                              icon:data.msgIcon,

                              time:data.msgTime

                            }); 

                        }

                    }

                });

                layer.close(index);

            });

        }

         

        //記錄進度

        function taskSchedule(n,id){

            $.ajax({

                type : "POST",

                async : false,

                dataType : "JSON",

                cache : false,

                url : "${basePath}/task/remschedule.htm",

                data :  {"schedule":n, "id":id},

                success : function(data) {}

            });

        }

    </script>

</body>

</html>

三、分頁類

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

package com.ebd.application.common.Base;

 

import java.util.List;

import java.util.Map;

 

public class Page<T> {

 

    /** 總記錄數 */

    private int total;

    /** 分頁結果 */

    private List<T> dataList;

    /** 開始頁碼 */

    private int start;

    /** 每頁多少 */

    private int limit;

    /** 查詢條件 */

    private Map<String,Object> condition;

     

    private int currentPage;    //當前頁

    private int currentIndex;   //當前記錄起始索引

    private int totalPage;      //總頁數

     

    public Page(int start, int limit) {

        this.start = start;

        this.limit = limit;

    }

     

    public Page(int start, int limit, Map<String,Object> condition) {

        this.start = start;

        this.limit = limit;

        this.condition = condition;

    }

 

    public int getCurrentPage() {

        if(currentPage<=0) currentPage = 1;

        return currentPage;

    }

 

    public void setCurrentPage(int currentPage) {

        this.currentPage = currentPage;

    }

 

    public int getCurrentIndex() {

        this.currentIndex = (getCurrentPage()-1)*getLimit();

        if(currentIndex<0) currentIndex = 0;

        return currentIndex;

    }

 

    public void setCurrentIndex(int currentIndex) {

        this.currentIndex = currentIndex;

    }

 

    public int getTotalPage() {

        return totalPage;

    }

 

    public void setTotalPage(int totalPage) {

        this.totalPage = totalPage;

    }

 

    public int getTotal() {

        return total;

    }

 

    public void setTotal(int total) {

        if(total%limit==0)

            totalPage = total/limit;

        else

            totalPage = total/limit+1;

        this.total = total;

    }

 

    public List<T> getDataList() {

        return dataList;

    }

 

    public void setDataList(List<T> dataList) {

        this.dataList = dataList;

    }

 

    public int getStart() {

        return start;

    }

 

    public void setStart(int start) {

        this.start = start;

    }

 

    public int getLimit() {

        return limit;

    }

 

    public void setLimit(int limit) {

        this.limit = limit;

    }

 

    public Map<String, Object> getCondition() {

    return condition;

    }

 

    public void setCondition(Map<String, Object> condition) {

    this.condition = condition;

    }

 

}

四、控制器

1

2

3

4

5

6

7

8

9

10

11

12

@ResponseBody

@RequestMapping("taskListByPage")

public Page<Task> listByPage(Integer start, Integer limit, String selectName, String selectStatus) {

     

    Map<String,Object> conditions = new HashMap<String,Object>();

    conditions.put("name", selectName);

    conditions.put("status", selectStatus);

    Page<Task> page = new Page<Task>(start,limit,conditions);

    page.setDataList(taskService.findByPage(page));

    page.setTotal(taskService.getCount(page));

    return page;

}

五、mapper

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<!-- 獲取總數 -->

<select id="getCount" resultType="int"

    select count(1) from bd_tasks

    where is_del = 0

    <if test="condition.name != ''">

        and t_name like concat('%',#{condition.name,jdbcType=VARCHAR},'%')

    </if>

    <if test="condition.status != ''">

        and t_status = #{condition.status,jdbcType=INTEGER}

    </if>

</select>

<!-- 分頁獲取記錄 -->

<select id="findByPage" resultMap="BaseResultMap">

    select

    <include refid="Base_Column_List" />

    from bd_tasks where is_del = 0

    <if test="condition.name != ''">

        and t_name like concat('%',#{condition.name,jdbcType=VARCHAR},'%')

    </if>

    <if test="condition.status != ''">

        and t_status = #{condition.status,jdbcType=INTEGER}

    </if>

    order by create_date desc,update_date desc

    limit #{start, jdbcType=INTEGER} , #{limit, jdbcType=INTEGER}

</select>

 效果圖

分類: [前端插件]

好文要頂 關注我 收藏該文

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章