springboot项目统一后端数据返回格式

spring boot自带的ResponseEntity

  1. ResponseEntity是springboot自带的返回格式封装类,使用起来也简单,和我们平时自己封装的差不多,大概的使用如下:
    springboot项目统一后端数据返回格式_第1张图片

自己封装类

  1. 和spring boot自带的类似,返回的无非就是data,code,message,其中data是个泛型,可以存放各种数据类型。封装类如下:
Data
public class ResultData {
    /** 结果状态 ,具体状态码参见ResultData.java*/
    private int code;
    private String message;
    private T data;

    public ResultData (){
        
    }
    public static  ResultData success(T data) {
        ResultData resultData = new ResultData<>();
        resultData.setCode(HttpStatus.RC200.getCode());
        resultData.setMessage(HttpStatus.RC200.getMessage());
        resultData.setData(data);
        return resultData;
    }

    public static  ResultData fail(int code, String message) {
        ResultData resultData = new ResultData<>();
        resultData.setCode(code);
        resultData.setMessage(message);
        return resultData;
    }

}
  1. 自己封装的HttpStatus枚举类。其实可以使用spring boot自带的HttpStatus,只是都是英文,对开发要求较高。
@AllArgsConstructor
public enum HttpStatusEnum {
    /**操作成功**/
    SUCCESS(200,"操作成功"),
    /**无权访问**/
    NO_PERMISSION(403,"无访问权限,请联系管理员授予权限"),
    /**匿名访问资源失败**/
    ACCESS_FAILED(401,"匿名用户访问无权限资源时的异常"),
    /**服务异常**/
    FAIL(500,"系统异常,请稍后重试"),
    INVALID_TOKEN(2001,"访问令牌不合法"),
    ACCESS_DENIED(2003,"没有权限访问该资源"),
    CLIENT_AUTHENTICATION_FAILED(1001,"客户端认证失败"),
    USERNAME_OR_PASSWORD_ERROR(1002,"用户名或密码错误"),
    UNSUPPORTED_GRANT_TYPE(1003, "不支持的认证模式");
    /**自定义状态码**/
    private final int code;
    /**自定义描述**/
    private final String message;
    public int getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
}
  1. 随后就是对controller层进行统一处理,使用注解RestControllerAdvice,对返回的数据进行统一的封装后返回。
@RestControllerAdvice(basePackages = "com.nchu.weather.controller")
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return true;
    }
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body instanceof String){
            return objectMapper.writeValueAsString(ResultData.success(body));
        }
        // 防止二次封装
        if(body instanceof ResultData){
            return body;
        }
        return ResultData.success(body);
    }
}
 
  
  1. 都搞定以后,可以写几个接口试一下了。下列是示例:

@RestController
@RequestMapping("/weather")
public class WeatherRestController {
    @Autowired
    private WeatherDataService weatherDataService;
    @GetMapping
    public WeatherVO getWeather(@RequestParam("name") String name){
        WeatherResponseVO weatherResponseVO =  weatherDataService.getDataByCityName(name);
        WeatherVO weatherVO = null;
        if (1000 == weatherResponseVO.getStatus()){
             weatherVO = weatherResponseVO.getData();
        }
        return weatherVO;
    }
}

结果自动被封装
springboot项目统一后端数据返回格式_第2张图片
部分对错误信息的统一处理相关类看这里:
https://blog.csdn.net/weixin_44632065/article/details/123031889
所使用的接口文档配置代码:
https://blog.csdn.net/weixin_44632065/article/details/122971425

你可能感兴趣的:(我的学习,springboot学习,spring,boot,后端,java,restful,json)