SpringBoot06 统一响应格式
1 要求
每个请求成功后,后台返回的响应格式都是一致的,例如:
2 创建一个视图模型
该模型用于格式化响应数据
package cn.xiangxu.springboottest.model.dataViewModel; import lombok.Data; @Data public class ResultViewModel<T> { private Integer code; private String message; private T data; }
3 创建一个视图模型工具类
该工具类根据传入的参数来实例化视图模型类
package cn.xiangxu.springboottest.utils; import cn.xiangxu.springboottest.model.dataViewModel.ResultViewModel; /** * 响应数据封装类 */ public class ResultViewModelUtil { /** * 请求成功方法01 * @param object 响应数据 * @return 视图模型实例 */ public static ResultViewModel success(Object object) { ResultViewModel resultViewModel = new ResultViewModel(); resultViewModel.setCode(0); resultViewModel.setMessage("请求成功"); resultViewModel.setData(object); return resultViewModel; } /** * 请求成功方法02 * @return 视图模型实例 */ public static ResultViewModel success() { return success(null); } /** * 请求失败方法01(捕获到的已知异常) * @param code 异常编号 * @param message 异常信息 * @return 视图模型实例 */ public static ResultViewModel error(Integer code, String message) { ResultViewModel resultViewModel = new ResultViewModel(); resultViewModel.setCode(code); resultViewModel.setMessage(message); resultViewModel.setData(null); return resultViewModel; } /** * 请求失败方法02(系统异常) * @return 视图模型实例 */ public static ResultViewModel error() { ResultViewModel resultViewModel = new ResultViewModel(); resultViewModel.setCode(-1); resultViewModel.setMessage("系统异常"); resultViewModel.setData("系统维护中..."); return resultViewModel; } }
4 利用视图模型工具类向前台返回格式化的JSON数据
package cn.xiangxu.springboottest.controller; import cn.xiangxu.springboottest.model.dataViewModel.ResultViewModel; import cn.xiangxu.springboottest.service.GirlService; import cn.xiangxu.springboottest.utils.ResultViewModelUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController @RequestMapping(value = "/girl") @Slf4j public class GirlController { @Resource(name = "girlService") private GirlService girlService; @GetMapping public ResultViewModel test() { log.info("hello boy"); return ResultViewModelUtil.success("响应数据"); // return ResultViewModelUtil.success(girlService.findAllGirl()); } }