标签:error pre 技术 getc http ret data get idt
idea中新建springboot项目
编写后端返回数据的封装类,如Result.java
public class Result<T> { private int code; private String msg; private T data; public static <T> Result<T> success(T data){ return new Result<T>(data); } public static <T> Result<T> error(CodeMsg codeMsg){ return new Result<T>(codeMsg); } private Result(T data) { this.code = 0; this.msg = "success"; this.data = data; } private Result(CodeMsg codeMsg) { if(codeMsg == null) { return; } this.code = codeMsg.getCode(); this.msg = codeMsg.getMsg(); } public int getCode() { return code; } public String getMsg() { return msg; } public T getData() { return data; } }
对状态码和状态信息封装为静态变量的类,如CodeMsg.java
public class CodeMsg { private int code; private String msg;
public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常"); private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } }
在controller中返回封装好的数据类型
@Controller @RequestMapping("/demo") public class DemoController { @RequestMapping("/hello") @ResponseBody public Result<String> hello() { return Result.success("hello 小老弟"); } @RequestMapping("/helloError") @ResponseBody public Result<String> helloError() { return Result.error(CodeMsg.SERVER_ERROR); } }
结果
标签:error pre 技术 getc http ret data get idt
原文地址:https://www.cnblogs.com/yanguobin/p/11624683.html