后端对返回数据的封装
Posted yanguobin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了后端对返回数据的封装相关的知识,希望对你有一定的参考价值。
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);
结果
以上是关于后端对返回数据的封装的主要内容,如果未能解决你的问题,请参考以下文章