ssm-crud项目

本文记录着我搭建ssm-crud项目时的主要代码实现,依次来熟悉ssm项目的搭建。github代码地址

前端页面代码

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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
/*引用jsp-api*/
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<title>员工列表</title>
<script src="${APP_PATH}/resources/js/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" href="${APP_PATH}/resources/bootstrap/css/bootstrap.min.css">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<%--link rel="stylesheet" href="${APP_PATH}/resources/bootstrap/css/bootstrap-theme.min.css">--%>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="${APP_PATH}/resources/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<%--搭建显示页面--%>
<div class="container">
<%--标题--%>
<div class="row">
<div class="col-md-12">
<h1>SSM-CRUD</h1>
</div>
</div>
<%--按钮--%>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button id="table_add" type="button" class="btn btn-primary btn" data-target="#myModal">
新增
</button>
<button id="table_del" class="btn btn-danger">删除</button>
</div>
</div>
<%--显示表格数据--%>
<div class="row">
<div class="col-md-12">
<%--设置表的网格状:table-bordered--%>
<table class="table table-hover" id="emps_table">
<thead>
<tr>
<th checkbox="true">ID</th>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>DeptName</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>

<%--显示分页信息--%>
<div class="row">
<%--分页文字信息--%>
<div class="col-md-6" id="page_info_area"></div>
<%--分页条信息--%>
<div class="col-md-6" id="page_nav_area">
<nav aria-label="Page navigation">
</nav>
</div>
</div>
</div>

<%--员工修改的模态框--%>
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title">员工修改</h4>
</div>
<div class="modal-body">
<p>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">EmpName</label>
<div class="col-sm-10">
<%-- 只读:Readonly--%>
<input type="text" name="empName" class="form-control" id="empName_update" Readonly
placeholder="请输入员工用户名">
<input type="hidden" name="empId" id="empId_update"/>
<%-- 静态实列--%>
<%--<p id="empName_update" class="form-control-static"></p>--%>
<%--添加校验信息--%>
<span></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="email_update"
placeholder="请输入合法邮箱">
<%--添加校验信息--%>
<span></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<%--多选框--%>
<label class="radio-inline">
<input type="radio" name="gender" id="gender1_update" value="1" checked>
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2_update" value="2">
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">DeptName</label>
<div class="col-sm-4">
<%--部门提交部门id--%>
<select class="form-control" name="deptId"></select>
</div>
</div>
</form>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="btn_update">更新</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<%--员工添加的模态框--%>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title">员工添加</h4>
</div>
<div class="modal-body">
<p>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">EmpName</label>
<div class="col-sm-10">
<input type="text" name="empName" class="form-control" id="empName_add"
placeholder="请输入员工用户名">
<%--添加校验信息--%>
<span></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="empEmail_add"
placeholder="请输入合法邮箱">
<%--添加校验信息--%>
<span></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<%--多选框--%>
<label class="radio-inline">
<input type="radio" name="gender" id="gender1_add" value="1" checked>
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2_add" value="2">
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">DeptName</label>
<div class="col-sm-4">
<%--部门提交部门id--%>
<select class="form-control" name="deptId"></select>
</div>
</div>
</form>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="model_save">保存</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
<script type="application/javascript">
//定义一个总记录数,为了后面新增后直接跳转到最后一页
var totalRecord;
// $(function () ncaught TypeError: e.indexOf is not a function
$(window).on('load', function () {
$("input[name='checkbox']").prop("checked", true);
});
// window.onload = function () ,同页面加载就会调函数
window.onload = function () {
$("tr:checkbox").prop("checked", this.checked);
to_page(1);
};

function to_page(page) {
$.ajax({
url: '/emps',
dataType: 'json',
data: "page=" + page,
type: 'get',
success: function (result) {
if (result.code === 0) {
//解析并显示员工数据
build_emps_table(result);
//将总记录数复制给全局变量
totalRecord = result.pageInfo.total;
//解析并显示分页信息
build_page_info(result);
//解析并显示分页条数据
build_page_nav(result);
}
}
})
}

function build_emps_table(result) {
var emps = result.pageInfo.list;
//清空元素
$("#emps_table tbody").empty();
$.each(emps, function (index, item) {
var empId = $("<td></td>").append(item.empId);
var empName = $("<td></td>").append(item.empName);
var gender = $("<td></td>").append(item.gender ? '男' : '女');
var email = $("<td></td>").append(item.email);
var deptName = $("<td></td>").append(item.department.deptName);
var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
.append("<span style='padding-right: 3px;'></span>").addClass("glyphicon glyphicon-paperclip")
.append("编辑");
//为每一行的编辑按钮添加一个属性,赋值给它
editBtn.attr("edit-id", item.empId);
var delBtn = $("<button></button>").addClass("btn btn-primary btn-sm delete_btn")
.append("<span style='padding-right: 3px;'></span>").addClass("glyphicon glyphicon-trash")
.append("删除");
var btnOperation = $("<td></td>").append(editBtn).append(delBtn);
//append方法执行后还是返回的原来的元素
$("<tr></tr>").append(empId)
.append(empName)
.append(email)
.append(gender)
.append(deptName)
.append(btnOperation)
.appendTo("#emps_table tbody");
})
}

/*解析显示分页信息*/
function build_page_info(result) {
//清空元素方法,避免重复添加数据,成倍增长
$("#page_info_area").empty();
$("#page_info_area").append("当前" + result.pageInfo.pageNum + "页,总" + result.pageInfo.pages + "页,总记录数" + result.pageInfo.total);
}

/*解析显示分页条*/
function build_page_nav(result) {
//清空元素方法,避免重复添加数据,成倍增长
$("#page_nav_area").empty();
var ul = $("<ul></ul>").addClass("pagination");
//首页的li
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr('href', '#'));
var prePageLi = $("<li></li>").append($("<a></a>").append("<span></span>").append("&laquo;"));
//判断是否有上一页,为false就是首页,禁用
if (result.pageInfo.hasPreviousPage == false) {
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
} else {
//为首页提供翻页
firstPageLi.click(function () {
to_page(1)
});
//为前一页提供翻页
prePageLi.click(function () {
to_page(result.pageInfo.pageNum - 1);
});
}
var nextPageLi = $("<li></li>").append($("<a></a>").append("<span></span>").append("&raquo;"));
//末页的li
var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr('href', '#'));
//如果为尾页,没有下一页,就禁用,也就不需要click函数触发
if (result.pageInfo.hasNextPage == false) {
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
} else {
//为下一页提供翻页
nextPageLi.click(function () {
to_page(result.pageInfo.pageNum + 1);
});
//为末页提供翻页
lastPageLi.click(function () {
to_page(result.pageInfo.pages);
});
}
//添加首页和上一页在分页条中
ul.append(firstPageLi).append(prePageLi);
//遍历当前需要的导航条页码数,ep:1,2,3,4,5
$.each(result.pageInfo.navigatepageNums, function (index, item) {
var numLi = $("<li></li>").append($("<a></a>").append(item));
//如果当前页码等于正在显示数据的页面,就激活图标颜色
if (result.pageInfo.pageNum == item) {
numLi.addClass("active");
}
numLi.click(function () {
to_page(item);
});
ul.append(numLi);
});
//添加下一页和尾页在分页条中
ul.append(nextPageLi).append(lastPageLi);
var navEle = $("<nav></nav>").append(ul);
navEle.appendTo("#page_nav_area");
}
</script>
<script type="text/javascript">
//点击新增按钮,弹出模态框
$("#table_add").click(function () {
//重置表单数据,但是span里的信息、input框颜色仍然有
$("#myModal form")[0].reset();
//清空span信息,重置input颜色
show_validate_msg("#empName_add", null, null);
show_validate_msg("#empEmail_add", null, null);
//查出下拉框里的部门名字
getDepts("#myModal select");
$('#myModal').modal({
//点击背景空白处不被关闭;
backdrop: 'static',
//触发键盘esc事件时不关闭。
keyboard: false
});
});

//校验员工添加的表单数据
function validate_add_form() {
//1.拿到想要的数据,校验. 前端校验用户名
var empName = $("#empName_add").val();
//6-16位 或者 2-5位中文
var regName = /(^[a-z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
if (!regName.test(empName)) {
show_validate_msg("#empName_add", "error", "需要输入6-16位字母和数字或者2-5位中文的组合");
return false;
} else {
show_validate_msg("#empName_add", "success", "");
}
var email = $("#empEmail_add").val();
//双斜杠,转义
var regEmail = /^([a-z0-9_-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/;
if (!regEmail.test(email)) {
show_validate_msg("#empEmail_add", "error", "邮箱格式不合法");
return false;
} else {
show_validate_msg("#empEmail_add", "success", "");
}
return true;
}

//显示校验信息
function show_validate_msg(ele, status, msg) {
//每次点击都需要清空先前添加的元素
$(ele).parent().removeClass("has-success has-error");
$(ele).next("span").text();
if (status == "success") {
$(ele).parent().addClass("has-success");
$(ele).next("span").text(msg);
} else if (status == "error") {
$(ele).parent().addClass("has-error");
$(ele).next("span").text(msg);
} else {
$(ele).next("span").text(msg);
}
}

//校验用户名是否可用,无重复
$("#empName_add").change(function () {
//获取员工用户名输入框的值, this表示当前#empName_add,这个含此id的对象html标签
var empName = this.value;
$.ajax({
url: '/checkName',
data: 'empName=' + empName,
type: 'post',
dataType: 'json',
success: function (rs) {
if (rs.code === 0) {
show_validate_msg("#empName_add", "success", rs.msg);
$("#model_save").attr("is_save", "success");
} else {
show_validate_msg("#empName_add", "error", rs.msg);
$("#model_save").attr("is_save", "error");
}
}
})
});

//监听表头新增里模态框的保存按钮
$("#model_save").click(function () {
//序列化表单数据,
var data = $("#myModal form").serialize();
//校验数据
if (!validate_add_form()) {
return false;
}
//检验是否有无错误信息,若有则不允许提交
if ($(this).attr("is_save") == "error") {
return false;
}
$.ajax({
url: '/save',
type: 'post',
dataType: 'json',
data: data,
success: function (rs) {
if (rs.code === 0) {
//关闭模态框,注意顺序
$('#myModal').modal('hide');
//返回到最后一页,显示添加的数据
to_page(totalRecord);
} else {
console.log(rs);
if (rs.error.empName != undefined) {
console.log(rs.error.empName);
show_validate_msg("#empName_add", "error", rs.error.empName);
}
if (rs.error.email != undefined) {
show_validate_msg("#email_add", "error", rs.error.email);
}
}
}
})
});

//查出所有的部门信息并显示在x下拉列表中
function getDepts(ele) {
//重置下拉框的值
$(ele).empty();
$.ajax({
url: '/depts',
type: 'get',
dataType: 'json',
success: function (rs) {
if (rs.code === 0) {
//显示部门信息在下拉框
$.each(rs.depts, function () {
var optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptId);
optionEle.appendTo(ele)
})
}
}
})
}
</script>
<script type="text/javascript">
//员工修改的模态框
//1.我们是按钮创建前就绑定click事件,所以绑定不上 或者直接在 c:forEach 遍历时就添加onclick();
//在生成的动态标签 $.each()里不建议使用onclick函数,不像thymeleaf遍历时还可以传值,这个用item.名称,显示item未定义
$(document).on("click", ".edit_btn", function () {
//得到员工信息
getEmp($(this).attr('edit-id'));
//得到下拉框的部门信息
getDepts("#updateModal select");
$("#updateModal").modal({
backdrop: 'static'
})
});
//遍历时添加函数onclik=edit()
// function edit() {
// var empId = $(".edit_btn").attr('edit-id');
// getEmp(empId);
// getDepts("#updateModal select");
// $("#updateModal").modal({
// backdrop: 'static'
// })
// }

function getEmp(empId) {
//直接赋值在url中,取不到数据
//var empId = $(".edit_btn").attr('edit-id');
$.ajax({
url: '/emp/' + empId,
dataType: 'json',
type: 'get',
success: function (rs) {
//清楚邮箱校验消息
show_validate_msg("#email_update", null, null);
if (rs.code === 0) {
var empData = rs.emp;
$("#empName_update").val(empData.empName);
$("#email_update").val(empData.email);
$("#updateModal input[name=gender]").val([empData.gender]);
$("#updateModal select").val([empData.deptId]);
$("#empId_update").val(empData.empId);
}
}
})
}

$("#btn_update").click(function () {
//序列化表单数据,
var data = $("#updateModal form").serialize();
$.ajax({
url: '/update',
type: 'post',
dataType: 'json',
data: data + "&_method=PUT",
success: function (rs) {
if (rs.code !== 0) {
console.log(rs);
if (rs.error.email != undefined) {
show_validate_msg("#email_update", "error", rs.error.email);
}
} else {
//关闭模态框,注意顺序
$('#updateModal').modal('hide');
//返回到最后一页,显示添加的数据
to_page(totalRecord);
}
}
})
})
</script>
</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
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
package cn.blue.controller;

import java.util.HashMap;
import java.util.Map;

import cn.blue.bean.Employee;
import cn.blue.service.EmployeeService;
import cn.blue.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.List;

/**
* @author Blue
* Date: 2019/12/17
*/
@Controller
public class EmployeeController {
@Resource
EmployeeService employeeService;

/**
* 跳转到emps页面
* @return
*/
@RequestMapping("/list")
public String home() {
return "emps";
}

/**
* 获取所有员工信息
* @param page
* @return
*/
@ResponseBody
@RequestMapping("/emps")
public Result getEmpsWithJson(@RequestParam(value = "page", defaultValue = "1") Integer page) {
//在查询之前只需调用,传入页码,每页数据量
PageHelper.startPage(page, 5);
List<Employee> emps = employeeService.getAll();
//使用pageInfo包装后的结果,只需要将pageInfo传给页面就好了
//封装了详细的分页信息,包括我们查询出来的数据,传入连续显示的页数
PageInfo pageInfo = new PageInfo(emps, 5);
return Result.success().add("pageInfo", pageInfo).setMsg("查询成功");
}

/**
* 根据员工id获取员工信息
* @param empId 员工id
* @return Emp员工信息
*/
@ResponseBody
@GetMapping("/emp/{empId}")
public Result getEmp(@PathVariable("empId") Integer empId){
try {
Employee emp = employeeService.getEmp(empId);
return Result.success().setMsg("查询成功").add("emp",emp);
} catch (Exception e) {
e.printStackTrace();
return Result.error(500).setMsg("查询失败").add("error",e.getMessage());
}
}

/**
* 员工信息修改
*
* @param employee 员工信息
*/
@PutMapping("/update")
@ResponseBody
public Result updateEmp(@Valid Employee employee, BindingResult result) {
if (result.hasErrors()) {
Map<String, Object> map = new HashMap<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError fieldError : errors
) {
//错误信息,错误字段
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return Result.error(500).setMsg("保存失败").add("error", map);
} else {
try {
employeeService.updateEmp(employee);
return Result.success().setMsg("保存成功");
} catch (Exception e) {
e.printStackTrace();
return Result.error(500).setMsg("保存失败").add("error", e.getMessage());
}
}
}

@RequestMapping("/find")
public String getEmps(@RequestParam(value = "page", defaultValue = "1") Integer page, ModelMap map) {
//在查询之前只需调用,传入页码,每页数据量
PageHelper.startPage(page, 5);
List<Employee> emps = employeeService.getAll();
//使用pageInfo包装后的结果,只需要将pageInfo传给页面就好了
//封装了详细的分页信息,包括我们查询出来的数据,传入连续显示的页数
PageInfo pageInfo = new PageInfo(emps, 5);
map.put("pageInfo", pageInfo);
return "list";
}

/**
* 员工信息保存
*
* @param employee 员工信息
*/
@PostMapping("/save")
@ResponseBody
public Result saveEmp(@Valid Employee employee, BindingResult result) {
if (result.hasErrors()) {
Map<String, Object> map = new HashMap<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError fieldError : errors
) {
//错误信息,错误字段
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return Result.error(500).setMsg("保存失败").add("error", map);
} else {
employeeService.saveEmp(employee);
return Result.success().setMsg("保存成功");
}
}

//检验员工用户名是否存在
@PostMapping("/checkName")
@ResponseBody
public Result checkName(@RequestParam("empName") String empName) {
String regx = "(^[a-z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})$";
if(!empName.matches(regx)){
return Result.error(500).setMsg("需要输入6-16位字母和数字或者2-5位中文的组合");
}
boolean b = employeeService.checkName(empName);
if (b) {
return Result.success().setMsg("此用户名可用");
}
return Result.error(500).setMsg("此用户名重复");
}
}
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
package cn.blue.controller;

import cn.blue.bean.Department;
import cn.blue.service.DepartmentService;
import cn.blue.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
* @author Blue
* Date: 2019/12/19
* 处理和部门有关的请求
*/
@Controller
@RequestMapping("/depts")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;


/**
* 查出部门所有信息
*/
@GetMapping
@ResponseBody
public Result getDepts(){
List<Department> list = departmentService.getDepts();
return Result.success().add("depts",list).setMsg("查询成功");
}

}

逆向工程使用

  1. MBGTest
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
package cn.blue.test;

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

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
* @author Blue
* Date: 2019/12/17
*/
public class MBGTest {
public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.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);
}
}
  1. mbg.xml
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
<?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="DB2Tables" targetRuntime="MyBatis3">

<!--表示在mybatis逆向工程是不需要添加注释-->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>

<!--配置数据库连接-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
userId="账号"
password="密码"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>

<!--指定javaBean生成位置: .\src\main\java-->
<javaModelGenerator targetPackage="cn.blue.bean" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>

<!--指定sql映射文件生成的位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

<!--指定接口生成的位置,比如mapper接口-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.blue.dao" targetProject="src/main/java"/>

<!--table表,指定每个表生成策略-->
<table tableName="tbl_emp" domainObjectName="Employee"/>
<table tableName="tbl_dept" domainObjectName="Department"/>

</context>
</generatorConfiguration>
  1. pom.xml
1
2
3
4
5
6
<!--mybatis的逆向工程-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
  1. 结果
    bean层生成

    • 指定sql映射文件生成的位置
      在这里插入图片描述
      在这里插入图片描述
  • 指定接口生成的位置,比如mapper接口
    在这里插入图片描述
    在这里插入图片描述

curd-调用mapper方法进行数据库操作

  1. MapperTest
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
package cn.blue.mapper;


import cn.blue.bean.Department;
import cn.blue.bean.Employee;
import cn.blue.dao.DepartmentMapper;
import cn.blue.dao.EmployeeMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.UUID;

/**
* @author Blue
* Date: 2019/12/17
* 推荐spring的项目,就可以使用spring的单元测试,可以自动注入我们需要的组件
* 1.导入Spring-Test模块
* 2.@ContextConfiguration指定的spring配置文件位置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
/**
* 测试DepartmentMapper
*/
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Autowired
SqlSession sqlSession;

@Test
public void testCurd(){
//1.创建SpringIoc容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从容器中获取mapper
DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
System.err.println("值:"+departmentMapper);
//1.插入部门
departmentMapper.insertSelective(new Department(null, "开发部"));
departmentMapper.insertSelective(new Department(null, "测试部"));
//2.生成员工数据,测试员工插入
employeeMapper.insertSelective(new Employee(null,"jerry",1,"Jerry@qq.com",1));
//3.批量插入员工数据
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String uid = UUID.randomUUID().toString().substring(0, 5) + i;
mapper.insertSelective(new Employee(null, uid, 1, uid + "@qq.com", 1));
}
System.out.println("批量完成");
}
}
  1. 依赖
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <!--junit单元测试,需要版本对应-->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>compile</scope>
    </dependency>
    <!--是一个为了测试为目的,且能组合成灵活表达式的匹配器类库-->
    <dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
    </dependency>
    <!--对Junit等测试框架的简单封装-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.7.RELEASE</version>
    </dependency>

    crud-配置文件

    在这里插入图片描述
  2. applicationContext.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">

<!--这里是spring的配置文件,主要配置业务和逻辑有关的东西-->
<context:component-scan base-package="cn.blue">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--数据源,事务控制,-->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--===========================-->
<!--配置和mybatis的整合-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定mybatis全局配置文件的位置-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="pooledDataSource"/>
<!--指定mybatis,mapper的位置-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--配置扫描器,将mybatis接口的实现加入到ioc容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有的dao接口,加入到ioc容器中-->
<property name="basePackage" value="cn.blue.dao"/>
</bean>
<!--配置一个可以执行批量的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sessionFactory"/>
<constructor-arg name="executorType" value="BATCH"/>
</bean>
<!--===========================-->
<!--事务控制的配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--控制数据源-->
<property name="dataSource" ref="pooledDataSource"/>
</bean>
<!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是配置式)-->
<aop:config>
<!--切入点表达式:service及其service子包下的都用事务控制-->
<aop:pointcut id="txPoint" expression="execution(* cn.blue.service..*(..))"/>
<!--配置事务增强, pointcut-ref指切入哪方法-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!--配置事务增强,事务如何切入-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有方法都是事务方法-->
<tx:method name="*"/>
<!--以get开始的所有方法-->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
  1. log4j.properties
1
2
3
4
5
6
7
8
9
10
# Global logging configuration
log4j.rootLogger=TRACE, stdout
# MyBatis logging configuration...
#TRACE->DEBUG->WRAN->ERROR
log4j.logger.cn.blue=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] - %m%n
  1. mybatis-config.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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>
<!--配置别名-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="cn.blue.bean"/>
</typeAliases>
<!--分页插件配置-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--分页合理化,页码正确:要是-1页就是首页-->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
  1. dispatcherServlet-servlet.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:component-scan base-package="cn.blue" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>

<!--两个配置-->
<!--将springmvc不能处理的请求交给tomcat-->
<mvc:default-servlet-handler/>
<!--能支持一些更高级的功能,JSR303校验,ajax等-->
<mvc:annotation-driven/>
</beans>
  1. web.xml
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
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--启动spring的容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--前端控制器,拦截所有请求-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--字符编码过滤器,一定要放在所有过滤器之前的-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncodingM</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--使用Rest风格的URI,将页面从普通的get/post请求转变成Put/delete方式-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
  1. dbconfig.properties
1
2
3
4
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=GMT%2b8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=账号
jdbc.password=密码
  1. pom.xml
    • 注意版本对应,不然可能会有兼容性问题
      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

      <dependencies>
      <!--spring相关的包-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <!--提供对AspectJ的支持,以便可以方便的将面向方面的功能集成进IDE中-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <!--spring mvc相关,实现SpringMVC的操作-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <!--spring提供对事务的支持,事务的相关处理以及实现类就在这个Jar包中-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <!--包含Spring 框架基本的核心工具类-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <!--junit单元测试,需要版本对应-->
      <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
      </dependency>
      <!--是一个为了测试为目的,且能组合成灵活表达式的匹配器类库-->
      <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
      <version>1.3</version>
      </dependency>
      <!--对Junit等测试框架的简单封装-->
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.7.RELEASE</version>
      </dependency>
      <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.28</version>
      </dependency>
      <!--导入mybatis-->
      <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.3</version>
      </dependency>
      <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.3</version>
      </dependency>
      <!--导入日志-->
      <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.26</version>
      </dependency>
      <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.5</version>
      </dependency>
      <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.10</version>
      </dependency>
      <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
      </dependency>
      <!--mybatis的逆向工程-->
      <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.5</version>
      </dependency>
      <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
      </dependency>
      <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
      </dependency>
      <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      </dependency>
      <!--转换解析json-->
      <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
      </dependency>
      <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.8</version>
      </dependency>
      <!--JSR303数据校验-->
      <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.18.Final</version>
      </dependency>
      </dependencies>

JSR303数据校验

  1. 添加bean层校验规则

    1
    2
    3
    4
    5
    6
    7
    @Pattern(regexp = "(^[a-z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})",
    message = "用户名需要输入6-16位字母和数字或者2-5位中文的组合\"")

    //@Email
    @Pattern(regexp = "^([a-z0-9_.-]+)@([\\da-z.-]+)\\.([a-z.]{2,6})$" ,
    message = "邮箱格式不合法")
    private String email;
  2. 获取校验信息

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public Result saveEmp(@Valid Employee employee, BindingResult result) {
    if (result.hasErrors()) {
    Map<String, Object> map = new HashMap<>();
    List<FieldError> errors = result.getFieldErrors();
    for (FieldError fieldError : errors
    ) {
    //错误信息,错误字段
    map.put(fieldError.getField(), fieldError.getDefaultMessage());
    }
    return Result.error(500).setMsg("保存失败").add("error", map);
    } else {
    employeeService.saveEmp(employee);
    return Result.success().setMsg("保存成功");
    }
    }
  3. 导入依赖

    1
    2
    3
    4
    5
    6
    <!--JSR303数据校验-->
    <dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.18.Final</version>
    </dependency>

    自定义封装Ajax返回值

    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
    package cn.blue.utils;

    import java.util.HashMap;

    /**
    * 用于ajax
    *
    * @author Blue
    *
    */
    public class Result extends HashMap<String, Object> {

    /**
    *
    */
    private static final long serialVersionUID = 1L;

    private Result() {
    }

    public static Result success() {
    return new Result().setCode(0);
    }

    public static Result error(int code) {
    return new Result().setCode(code);
    }

    public Result add(String key, Object value) {
    this.put(key, value);
    return this;
    }

    public Result setCode(int code) {
    this.put("code", code);
    return this;
    }

    public int getCode() {
    return this.getValue("code");
    }

    public Result setMsg(String msg) {
    this.put("msg", msg);
    return this;
    }

    public String getMsg() {
    return this.getValue("msg");
    }

    public <T> T getValue(String key) {
    return (T) this.get(key);
    }
    }
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  1. © 2020 Liu Yang    湘ICP备20003709号

请我喝杯咖啡吧~

支付宝
微信