/**
* @author StormMa
* @Date 2017-03-21
*/
生命不息,奋斗不止!
之所以讲究规范会请求处理,就是将每次的后端处理结果封装成固定的格式去回送到前端,之于规范化的好处,就不甚枚举了。我们先看看代码实现吧!
定义结果集的规范
/**
* <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 + '\'' +
'}';
}
}
结果集封装
/**
* <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;
}
}
举例
/**
* <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里面的代码更加简洁明了!