• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

springboot 搞代码 4年前 (2022-01-09) 48次浏览 已收录 0个评论

 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;
  /** 数据 */
  pr<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码网*</b>ivate Object data;
  /** 请求地址 */
  private String url;

  ......
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解SpringBoot定制@ResponseBody注解返回的Json格式
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址