数据格式化的好处: 统一标准,降低接口数据结构的复杂度的,有利于接口的前端调用
Java实现:
1、定义返回状态码,一般采用的方式有接口、常量类、枚举
/**
* 定义返回数据的状态码
*/
public interface ResultCode {
public static Integer SUCCESS = 20000; // 成功
public static Integer ERROR = 20001; // 失败
}
2、定义返回的数据结构
/**
* 定义返回数据的格式
*/
@Data
public class R {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
//把构造方法私有
private R() {}
//成功静态方法
public static R ok() {
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
//失败静态方法
public static R error() {
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public R success(Boolean success){
this.setSuccess(success);
return this;
}
public R message(String message){
this.setMessage(message);
return this;
}
public R code(Integer code){
this.setCode(code);
return this;
}
public R data(String key, Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map){
this.setData(map);
return this;
}
}
3、测试接口
mport com.xcm.commonutils.R;
import com.xcm.eduservice.entity.EduTeacher;
import com.xcm.eduservice.service.EduTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 讲师 前端控制器
* </p>
*
* @author testjava
* @since 2020-06-15
*/
@Api(description = "讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
// 注入service
@Autowired
private EduTeacherService teacherService;
// 查询所有讲师数据
@ApiOperation(value = "所有讲师列表")
@GetMapping("findAll")
public R findAllTeacher(){
List<EduTeacher> list = teacherService.list(null);
return R.ok().data("items", list);
}
// 逻辑删除讲师
@ApiOperation(value = "逻辑删除讲师")
@DeleteMapping("{id}")
public R removeTeacher(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id){
boolean flag = teacherService.removeById(id);
if (flag) {
return R.ok();
} else {
return R.error();
}
}
}