SpringBoot RESTful API返回統一數據格式還不懂?

關於 Spring 的全局處理,有兩方面要說:前端

統一數據返回格式
統一異常處理
爲了將兩個問題說明清楚,將分兩個章節分別說明,本章主要說第一點
有童鞋說,咱們項目都作了這種處理,就是在每一個 API 都單獨工具類將返回值進行封裝,但這種不夠優雅;我想寫最少的代碼完成這件事,也許有童鞋說,加幾個註解就解決問題了,說的沒錯,但這篇文章主要是爲了說明爲何加了幾個註解就解決問題了,目的是但願你們知其因此然。web

爲了更好的說明問題,本文先說明如何實現,而後再詳細剖析實現原理(這很關鍵)後端

爲何要作統一數據返回格式api

先後端分離是當今服務形式的主流,如何讓前端小夥伴能夠處理標準的 response JSON 數據結構都相當重要,爲了讓前端有更好的邏輯展現與頁面交互處理,每一次 RESTful 請求都應該包含如下幾個信息:瀏覽器

名稱數據結構

描述app

status前後端分離

狀態碼,標識請求成功與否,如 [1:成功;-1:失敗]ide

errorCode工具

錯誤碼,給出明確錯誤碼,更好的應對業務異常;請求成功該值可爲空

errorMsg

錯誤消息,與錯誤碼相對應,更具體的描述異常信息

resultBody

返回結果,一般是 Bean 對象對應的 JSON 數據, 一般爲了應對不一樣返回值類型,將其聲明爲泛型類型 實現

通用返回值類定義

根據上面的描述,用 Java Bean 來體現這個結構就是這樣:

@Data

public final class CommonResult<T> {

private int status = 1;

private String errorCode = "";

private String errorMsg = "";

private T resultBody;

public CommonResult() {

}

public CommonResult(T resultBody) {

SpringBoot RESTful API返回統一數據格式還不懂?
SpringBoot RESTful API返回統一數據格式還不懂?

}

}

配置

沒錯,咱們須要藉助幾個關鍵注

@EnableWebMvc

@Configuration

public class UnifiedReturnConfig {

@RestControllerAdvice("com.example.unifiedreturn.api")

static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object>{

@Override

public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {

return true;

}

@Override

public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

if (body instanceof CommonResult){

return body;

}

return new CommonResult<Object>(body);

}

}

}

dy);

}

}

}

到這裏就結束了,咱們就能夠縱情的寫任何 RESTful API 了,全部的返回值都會有統一的 JSON

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("")

public List<UserVo> getUserList(){

List<UserVo> userVoList = Lists.newArrayListWithCapacity(2);

userVoList.add(UserVo.builder().id(1L).name("一米八的一小夥").age(18).build());

userVoList.add(UserVo.builder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

lder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

}

@GetMapping("/{id}")

public UserVo getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小夥").age(18)

getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小夥").age(18).

e("一米八的一小夥").age(18).

@GetMapping("/testResponseEntity")

public ResponseEntity getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小夥").age(18).build(), H

ty getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小夥").age(18).build(), HttpStatus.OK);

}

d(), HttpStatus.OK);

}

打開瀏覽器輸入地址測試: http://localhost:8080/users/testR

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

@Documented

@Import(DelegatingWebMvcConfiguration.class)

public

icy.RUNTIME)

@Target(ElementType.TYP

ME)

@Target(ElementType.TYPE)

@Doc

TYPE)

@Doc

@Configuration

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

...

}

引入了 DelegatingWebMvcConfiguration.class,那來看這個類吧:

@Configurat

@Bean

public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {

RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();

...

return adapter;

}

lic RequestMappingHandlerAdapte

public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter

implements BeanFactoryAware, InitializingBean {

...

}

RequestMappingHandlerAdapter 是每一次請求處理的關鍵,來看該類的定義:

public class RequestMappingHandlerAdapter extends AbstractHandle

@Override

public void afterPropertiesSet() {

// Do this first, it may add ResponseBody advice beans

initControllerAdviceCache();

if (this.argumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();

this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.initBinderArgumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();

this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.returnValueHandlers == null) {

List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();

this.returnValueHandlers = new HandlerMethodReturnValueHandlerCompos

ull) {

L

andlers(handle

ull) {

L

}

ull) {

L

private void initControllerAdviceCache() {

...

if (logger.isInfoEnabled()) {

logger.info("Looking for @ControllerAdvice: " + getApplicationContext());

}

List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());

AnnotationAwareOrderComparator.sort(beans);

List<Object> requestResponseBodyAdviceBeans = new ArrayList<Object>();

for (ControllerAdviceBean bean : beans) {

...

if (ResponseBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {

requestRespon

(beans);

List<Object> requestRe

ns);

List<Object> requestResponseBodyAdviceBean

sponseBodyAdviceBean

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@Response

stResponseBodyAdviceBeans.add(bean);

stResponseBodyAdviceBeans.add(bean);

}

}

ceBeans.add(bean);

}

}

}

}

}

經過 ControllerAdviceBean 靜態方法掃描

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@ResponseBo

@ControllerAdvice

@ResponseBody

public @interfa

eBody

public @interface RestControllerAd

ce RestControllerAd

if (messageConverter instanceof GenericHttpMessageConverter) {

if (((GenericHttpMessageConverter) messageConverter).canWrite(

declaredType, valueType, selectedMediaType)) {

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType,

(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),

inputMessage, outputMessage);

...

return;

}

}

nericHttpMessageConve

pro

{

outputValue = (T) getAdvice().bef

{

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, retur

) getAdvice().beforeBodyWrite(outputValue, retur

class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyAdvice<Object> {

@Override

public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

return processBody(body, returnType, contentType, converterType, request, response);

}

@SuppressWarnings("unchecked")

private <T> Object processBody(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

e,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

contentType, converterType, reques

body, returnType,

contentType, converterType, request, response);

}

}

re

verterType, request, response);

}

}

return body;

}

}

);

}

}

return body;

}

}

}

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType);

if (handler == null) {

throw new IllegalArgumentException("Unknown return value type: " + returnType.g

Value, MethodParameter returnType,

ModelAndViewContainer mavContaine

meter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest)

iner, NativeWebRequest webRequest) throws Exception {

t) throws Exception {

HandlerMethodReturnVal

HandlerMethodReturnVal

@Override

public boolean supportsParameter(MethodParameter parameter

;

}

handler.handleReturnValue(returnValue, retur

;

}

handler.handleReturnValue(retu

;

}

handler.handleReturnValue(returnValue, returnType, mavContainer, webRequ

ue(returnValue, returnType, mavContainer, webRequ

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

...

if (responseEntity instanceof ResponseEntity) {

int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();

outputMessage.getServletResponse().setStatus(returnStatus);

if (returnStatus == 200) {

if (SAFE_METHODS.contains(inputMessage.getMethod())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody()

od())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

// Ens

ty.getBody(), returnType, inputMessage, outputMessage);

// Ensure headers are flushed even i

);

// Ensure headers are flushed even if no body was written.

outp

ed even if no body was written.

outputMessage.flush();

}

.

outputMessage.flush();

}

該方法提取出 responseEntity.getBody(),並傳遞個 MessageConverter,而後再繼續調用 beforeBodyWrite 方法,這纔是真相!!!

這是 RESTful API 正常返回內容的狀況

相關文章
相關標籤/搜索