请求规范化

@author StormMa
@Date 2017-03-21


生命不息,奋斗不止!

前言

之所以讲究规范会请求处理,就是将每次的后端处理结果封装成固定的格式去回送到前端,之于规范化的好处,就不甚枚举了。我们先看看代码实现吧!

定义结果集的规范

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
/**
* <p>Created on 2017/3/15.</p>
*
* @author StormMa
*
* @Description: 对请求结果进行封装
*/
public class RequestResult<T> {
/**
* error code :错误是1、成功是0
*/
private Integer code;
/**
* 要返回的数据
*/
private T data;
/**
* 本次请求的说明信息
*/
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "RequestResult{" +
"code=" + code +
", data=" + data +
", msg='" + msg + '\'' +
'}';
}
}

结果集封装

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
/**
* <p>Created on 2017/3/15.</p>
*
* @author StormMa
*
* @Description: 封装请求结果的工具类
*/
public class ResultUtil {
/**
* 成功请求的结果封装
* @param t
* @param <T>
* @return
*/
public static <T> RequestResult<T> success(T t) {
RequestResult<T> result = new RequestResult<>();
result.setCode(0);
result.setMsg("success");
result.setData(t);
return result;
}
/**
* 成功请求的结果封装
* @param <T>
* @return
*/
public static <T> RequestResult<T> success() {
return success(null);
}
/**
* 失败请求的结果封装
* @param <T>
* @return
*/
public static <T> RequestResult<T> fail() {
RequestResult<T> result = new RequestResult<>();
result.setCode(1);
result.setData(null);
result.setMsg("fail");
return result;
}
/**
* 失败请求的结果封装
* @param msg
* @param <T>
* @return
*/
public static <T> RequestResult<T> fail(String msg) {
RequestResult<T> result = new RequestResult<>();
result.setCode(1);
result.setData(null);
result.setMsg(msg);
return result;
}
}

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* <p>Created on 2017/3/21.</p>
*
* @author StormMa
*
* @Description: 使用规范化结果响应
*/
@RestController
@RequestMapping(value = "/test")
public class TestController {
@Autowired
private ITestService testService;
@RequestMapping(value = "/{testId}")
public RequestResult<Test> getTest(@PathVariable int testId) {
Test test = testService.getTestById(testId);
if (test != null) {
return ResultUtil.success(test);
}
return ResultUtil.fail("不存在数据!");
}
}

结尾

看到规范化请求响应的好处了吧,Controller里面的代码更加简洁明了!