详解SpringBoot定制@ResponseBody注解返回的Json格式

 更新时间:2020年11月06日 11:00:12   作者:烟囱里一只猫、  
这篇文章主要介绍了详解SpringBoot定制@ResponseBody注解返回的Json格式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

 1、引言

在SpringMVC的使用中,后端与前端的交互一般是使用Json格式进行数据传输,SpringMVC的@ResponseBody注解可以很好的帮助我们进行转换,但是后端返回数据给前端往往都有约定固定的格式,这时候我们在后端返回的时候都要组拼成固定的格式,每次重复的操作非常麻烦。

2、SpringMVC对@ResponseBody的处理

SpringMVC处理@ResponseBody注解声明的Controller是使用默认的.RequestResponseBodyMethodProcessor类来实现,RequestResponseBodyMethodProcessor类实现了HandlerMethodReturnValueHandler接口并实现了接口中的supportsReturnType()和handleReturnValue()方法。

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.method.support;

import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * Strategy interface to handle the value returned from the invocation of a
 * handler method .
 *
 * @author Arjen Poutsma
 * @since 3.1
 * @see HandlerMethodArgumentResolver
 */
public interface HandlerMethodReturnValueHandler {

 /**
 * Whether the given {@linkplain MethodParameter method return type} is
 * supported by this handler.
 * @param returnType the method return type to check
 * @return {@code true} if this handler supports the supplied return type;
 * {@code false} otherwise
 */
 boolean supportsReturnType(MethodParameter returnType);

 /**
 * Handle the given return value by adding attributes to the model and
 * setting a view or setting the
 * {@link ModelAndViewContainer#setRequestHandled} flag to {@code true}
 * to indicate the response has been handled directly.
 * @param returnValue the value returned from the handler method
 * @param returnType the type of the return value. This type must have
 * previously been passed to {@link #supportsReturnType} which must
 * have returned {@code true}.
 * @param mavContainer the ModelAndViewContainer for the current request
 * @param webRequest the current request
 * @throws Exception if the return value handling results in an error
 */
 void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;

}

3、实现思路

知道@ResponseBody是由RequestResponseBodyMethodProcessor进行处理的,这时候我们可以自己定义一个处理返回数据的Handler来实现我们的定制化Json格式数据返回,但是如果直接把我们定制的Handler加入到SpringMVC的ReturnValueHandlers中,因为我们定制的Handler在RequestResponseBodyMethodProcessor之后,所以我们定制的Handler还是不会生效,这时候我们可以想办法把RequestResponseBodyMethodProcessor替换成我们定制的Handler。

4、代码实现

4.1、定制Json返回格式实体

package com.autumn.template;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * JSON信息交互对象模板
 * @Author Autumn、
 * @Date 2019/4/8 23:46
 * @Description
 */
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Result implements BaseBean {

  ......(这里只展示一些必要字段)
  /** 响应码 */
  private Integer code;
  /** 响应信息 */
  private String message;
  /** 数据 */
  private Object data;
  /** 请求地址 */
  private String url;

  ......
}

4.2、定义定制Json返回格式Handler

package com.autumn.component.handler;

import com.autumn.template.Result;

import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 统一处理ResponseBody数据格式
 * @Author: Autumn、
 * @Date: 2019/4/24 23:59
 * @Description:
 **/
public class ResultWarpReturnValueHandler implements HandlerMethodReturnValueHandler {

  private final HandlerMethodReturnValueHandler delegate;

  /** 委托 */
  public ResultWarpReturnValueHandler(HandlerMethodReturnValueHandler delegate) {
    this.delegate = delegate;
  }

  /**
   * 判断返回类型是否需要转成字符串返回
   * @param returnType 方法返回类型
   * @return 需要转换返回true,否则返回false
   */
  @Override
  public boolean supportsReturnType(MethodParameter returnType) {
    return delegate.supportsReturnType(returnType);
  }

  /**
   * 返回值转换
   */
  @Override
  public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
   // 委托SpringMVC默认的RequestResponseBodyMethodProcessor进行序列化
    delegate.handleReturnValue(returnValue instanceof Result ? returnValue : Result.succeed(returnValue), returnType, mavContainer, webRequest);
  }
}

4.3、替换默认的RequestResponseBodyMethodProcessor

package com.autumn.config;

import com.autumn.component.handler.ResultWarpReturnValueHandler;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * 替换默认的RequestResponseBodyMethodProcessor
 * @Author Autumn、
 * @Date 2019/4/8 23:46
 * @Description
 */
@Slf4j
@Configuration
@EnableCaching
public class ApplicationContext implements WebMvcConfigurer, InitializingBean {

  @Autowired(required = false)
  private RequestMappingHandlerAdapter adapter;

  @Override
  public void afterPropertiesSet() throws Exception {
    // 获取SpringMvc的ReturnValueHandlers
    List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
    // 新建一个List来保存替换后的Handler的List
    List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(returnValueHandlers);
    // 循环遍历找出RequestResponseBodyMethodProcessor
    for (HandlerMethodReturnValueHandler handler : handlers) {
      if (handler instanceof RequestResponseBodyMethodProcessor) {
       // 创建定制的Json格式处理Handler
        ResultWarpReturnValueHandler decorator = new ResultWarpReturnValueHandler(handler);
        // 使用定制的Json格式处理Handler替换原有的RequestResponseBodyMethodProcessor
        int index = handlers.indexOf(handler);
        handlers.set(index, decorator);
        break;
      }
    }
    // 重新设置SpringMVC的ReturnValueHandlers
    adapter.setReturnValueHandlers(handlers);
  }
}

5、总结

至此完成了定制@ResponseBody注解返回的Json格式,在Controller中返回任何的字符串都可以定制成为我们想要的Json格式。此外SpringMVC还提供了非常多的Handler接口来进行Controller的增强,可以使用此思路对参数等进行定制化。

到此这篇关于详解SpringBoot定制@ResponseBody注解返回的Json格式的文章就介绍到这了,更多相关SpringBoot @ResponseBody返回Json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • JAVA中JVM的重排序详细介绍

    JAVA中JVM的重排序详细介绍

    重排序通常是编译器或运行时环境为了优化程序性能而采取的对指令进行重新排序执行的一种手段。重排序分为两类:编译期重排序和运行期重排序,分别对应编译时和运行时环境
    2014-05-05
  • Java深入浅出掌握SpringBoot之MVC自动配置原理篇

    Java深入浅出掌握SpringBoot之MVC自动配置原理篇

    在进行项目编写前,我们还需要知道一个东西,就是SpringBoot对我们的SpringMVC还做了哪些配置,包括如何扩展,如何定制,只有把这些都搞清楚了,我们在之后使用才会更加得心应手
    2021-10-10
  • Java 8 lambda表达式引入详解及实例

    Java 8 lambda表达式引入详解及实例

    这篇文章主要介绍了Java 8 lambda表达式引入详解及实例的相关资料,需要的朋友可以参考下
    2017-05-05
  • java配置多个过滤器优先级以及几个常用过滤器操作

    java配置多个过滤器优先级以及几个常用过滤器操作

    这篇文章主要介绍了java配置多个过滤器优先级以及几个常用过滤器的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • SpringBoot中使用 RabbitMQ的教程详解

    SpringBoot中使用 RabbitMQ的教程详解

    这篇文章主要介绍了SpringBoot中使用 RabbitMQ的教程详解,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • 在Eclipse安装Spring boot插件的步骤(图文)

    在Eclipse安装Spring boot插件的步骤(图文)

    这篇文章主要介绍了在Eclipse安装Spring boot插件的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 在jmeter的beanshell中用java获取系统当前时间的简单实例

    在jmeter的beanshell中用java获取系统当前时间的简单实例

    这篇文章介绍了在jmeter的beanshell中用java获取系统当前时间的简单实例,有需要的朋友可以参考一下
    2013-09-09
  • SpringBoot简单实现定时器过程

    SpringBoot简单实现定时器过程

    这篇文章主要介绍了SpringBoot简单实现定时器过程,对于Java后端来说肯定实现定时功能肯定是使用到Spring封装好的定时调度Scheduled
    2023-04-04
  • Hibernate延迟加载技术详解

    Hibernate延迟加载技术详解

    这篇文章主要介绍了Hibernate延迟加载技术,结合实例形式详细分析了Hibernate延迟加载所涉及的各种常用技巧,需要的朋友可以参考下
    2016-03-03
  • Java多态到底都有啥好处

    Java多态到底都有啥好处

    Java中的多态性有两种类型:编译时多态(静态绑定)和运行时多态(动态绑定)。方法重载是静态多态的一个例子,而方法重写是动态多态的一个例子,接下来通过本文给大家分享Java多态到底教了我干啥?有啥好处,一起了解下吧
    2021-05-05

最新评论