SpringBoot统一数据返回的几种方式
作者:码农阿豪@新空间代码工作室
在Web应用程序开发中,统一数据返回格式对于前后端分离项目尤为重要。通过统一的数据返回格式,可以大大简化前端数据解析的复杂度,提高代码的可维护性和一致性。本文将介绍如何在Spring Boot项目中实现统一的数据返回格式。
一、概念
统一数据返回指的是将所有接口的返回数据进行统一封装,使用一致的格式返回给前端。例如,可以定义一个标准的响应格式,包括状态码、消息、数据等信息:
{ "code": 200, "message": "Success", "data": { ... } }
通过这种方式,前端开发人员只需处理一种响应格式,减少解析错误和代码冗余。
二、实现统一数据返回
为了实现统一的数据返回格式,我们可以使用Spring Boot的ResponseBodyAdvice
接口,该接口可以在响应返回之前对响应体进行处理。
2.1 重写responseAdvice方法
首先,我们需要创建一个类,实现ResponseBodyAdvice
接口,并重写其中的方法:
import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class converterType) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof ResponseEntity) { return body; } return new ApiResponse(200, "Success", body); } }
在上面的代码中,supports
方法用于判断哪些接口的返回值需要处理,这里返回true
表示处理所有接口的返回值。beforeBodyWrite
方法则是在响应体写入之前进行处理,将返回的数据封装为统一格式的ApiResponse
对象。
2.2 实现ApiResponse类
创建ApiResponse
类,用于定义统一的响应格式:
public class ApiResponse<T> { private int code; private String message; private T data; public ApiResponse(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } // Getters and Setters }
三、特殊类型-String的处理
由于Spring在处理String
类型的返回值时,会直接将其写入响应体,而不会经过HttpMessageConverter
,因此我们需要对String
类型进行特殊处理:
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> { private final ObjectMapper objectMapper; public GlobalResponseAdvice(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof String) { try { return objectMapper.writeValueAsString(new ApiResponse<>(200, "Success", body)); } catch (Exception e) { throw new RuntimeException("Failed to write response as String", e); } } if (body instanceof ResponseEntity) { return body; } return new ApiResponse<>(200, "Success", body); } }
在上面的代码中,我们使用ObjectMapper
将ApiResponse
对象转换为String
,确保String
类型的返回值也能统一为标准格式。
四、全部代码
// ApiResponse.java public class ApiResponse<T> { private int code; private String message; private T data; public ApiResponse(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } // Getters and Setters } // GlobalResponseAdvice.java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> { private final ObjectMapper objectMapper; public GlobalResponseAdvice(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof String) { try { return objectMapper.writeValueAsString(new ApiResponse<>(200, "Success", body)); } catch (Exception e) { throw new RuntimeException("Failed to write response as String", e); } } if (body instanceof ResponseEntity) { return body; } return new ApiResponse<>(200, "Success", body); } }
通过上述代码,我们可以实现Spring Boot项目中统一的数据返回格式。无论返回的数据类型如何,都可以通过统一封装后的格式返回给前端,极大地提高了代码的可维护性和前后端的开发效率。
到此这篇关于SpringBoot统一数据返回的几种方式的文章就介绍到这了,更多相关SpringBoot统一数据返回内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!