在前后端分离的系统中,接口开发的时候需要有统一的返回格式,比如:
{
"code":200,
"msg":"success",
"data":"www.yxjc123.com"
}
这样前端在处理后端的返回结果时可以通过code值判断是否处理成功或失败等。比如:
- code为200表示成功;
- code为509表示失败。
然后通过data值获取后端的返回结果。
以下给出SpringBoot中统一返回格式例子:
1.定义返回状态码
package com.example.yxjc.resp;
public enum ResponseCode {
SUCCESS(200,"操作成功"),
ERROR(509,"操作失败"),
VALIDATE_ERROR(405,"校验错误"),
NOT_LOGIN(501,"未登录");
private int code;
private String desc;
ResponseCode(int code,String desc){
this.code = code;
this.desc = desc;
}
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}
2. 定义返回方法
package com.example.yxjc.resp;
public class Response<T> {
private int code;
private String msg;
private T data;
private long totalTime;
private Response(ResponseCode responseCode) {
this.code = responseCode.getCode();
this.msg = responseCode.getDesc();
}
private Response(ResponseCode responseCode,T data) {
this.code = responseCode.getCode();
this.msg = responseCode.getDesc();
this.data = data;
}
private Response(ResponseCode responseCode,String msg) {
this.code = responseCode.getCode();
this.msg = msg;
}
private Response(ResponseCode responseCode,String msg,T data) {
this.code = responseCode.getCode();
this.msg = msg;
this.data = data;
}
public static Response success() {
return new Response(ResponseCode.SUCCESS);
}
public static Response error() {
return new Response(ResponseCode.ERROR);
}
public static Response build(ResponseCode responseCode) {
return new Response(responseCode);
}
public static<T> Response<T> build(ResponseCode responseCode,T data) {
return new Response(responseCode,data);
}
public static Response build(ResponseCode responseCode,String msg) {
return new Response(responseCode,msg);
}
public static<T> Response<T> build(ResponseCode responseCode,String msg,T data) {
return new Response(responseCode,msg,data);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public long getTotalTime() {
return totalTime;
}
public void setTotalTime(long totalTime) {
this.totalTime = totalTime;
}
}
3. 在controller中使用我们定义的返回格式Response
@Controller
public class HelloController {
@ResponseBody
@GetMapping("/responseTest")
public Response responseTest() {
//测试返回结果
return Response.success();
}
}
浏览器访问地址http://localhost:8080/responseTest