欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-02 10:49:38
1、引言在springmvc的使用中,后端与前端的交互一般是使用json格式进行数据传输,springmvc的@responsebody注解可以很好的帮助我们进行转换,但是后端返回数据给前端往往都有约...

 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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!