web 数据返回内容格式 josn xml协商

发布于:2025-05-13 ⋅ 阅读:(9) ⋅ 点赞:(0)

一套系统适配多端数据返回
在这里插入图片描述

多端内容适配

默认规则

SpringBoot 多端内容适配。

  1. 基于请求头内容协商:(默认开启)

    客户端向服务端发送请求,携带HTTP标准的Accept请求头。Accept: application/jsontext/xmltext/yaml,服务端根据客户端请求头期望的数据类型进行动态返回

  2. 基于请求参数内容协商:(需要开启)

    发送请求 GET /projects/spring-boot?format=json,匹配到 @GetMapping("/projects/spring-boot"),根据参数协商,优先返回 json 类型数据【需要开启参数匹配设置】,发送请求 GET /projects/spring-boot?format=xml,优先返回 xml 类型数据

基于请求参数返回xml

引入支持写出xml内容依赖

<!-- 支持写出xml格式 -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

标注注解@JacksonXmlRootElement,可以写出为xml文档

@JacksonXmlRootElement
public class TUser {
    private Long id;
    private String loginName;
    private String nickName;
    private String passwd;
		
		// getter,setter
}

开启基于请求参数的内容协商

# spring配置
spring:
  # MVC配置
  mvc:
    # 内容协商配置
    content-negotiation:
      # 是否优先使用参数来决定返回类型,默认参数名:format
      favor-parameter: true
      # 用于指定返回类型参数的名称
      parameter-name: type

测试
在这里插入图片描述在这里插入图片描述

自定义内容返回yaml

引入支持yaml格式依赖

<!-- yaml格式支持 -->
<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

修改内容协商方式,自定义yaml内容类型

# spring配置
spring:
  # MVC配置
  mvc:
    # 内容协商配置
    content-negotiation:
      # 是否优先使用参数来决定返回类型,默认参数名:format
      favor-parameter: true
      # 用于指定返回类型参数的名称
      parameter-name: type
      # 默认返回类型
      default-content-type: application/json
      # 新增媒体类型
      media-types:
        # 指定yaml格式
        yaml: text/yaml

编写自定义的YAML类型HTTP消息转换器MyYamlHttpMessageConverter ,把对象写出成YAML

package com.keepc.bootyaml.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * 自定义的YAML类型HTTP消息转换器,继承自AbstractHttpMessageConverter。
 * 用于支持将对象转换为YAML格式,并能被Spring MVC框架在处理HTTP请求和响应时使用。
 */
public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private ObjectMapper objectMapper = null; // 用于对象到YAML的转换

    /**
     * 构造函数,初始化消息转换器,配置支持的媒体类型为text/yaml,并配置YAML序列化器。
     */
    public MyYamlHttpMessageConverter() {
        // 配置支持的媒体类型
        super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
        // 配置YAML工厂,禁用文档开始标记
        YAMLFactory factory = new YAMLFactory()
                .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
        this.objectMapper = new ObjectMapper(factory);
    }

    /**
     * 判断当前转换器是否支持指定的类。
     * 
     * @param clazz 待判断的类
     * @return 总是返回true,表示支持所有类型的对象转换。
     */
    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     * 读取HTTP消息体,将其转换为对象。此方法在处理@RequestBody注解时被调用。
     * 
     * @param clazz        目标对象的类
     * @param inputMessage HTTP输入消息
     * @return 转换后的对象
     * @throws IOException                     输入输出异常
     * @throws HttpMessageNotReadableException 消息不可读异常
     */
    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        return null; // 此处需要根据实际需求实现对象的读取和转换逻辑
    }

    /**
     * 将对象写入HTTP消息体。此方法在处理@ResponseBody注解时被调用。
     * 
     * @param methodReturnValue 方法返回值
     * @param outputMessage     HTTP输出消息
     * @throws IOException                     输入输出异常
     * @throws HttpMessageNotWritableException 消息不可写异常
     */
    @Override
    protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        // 使用try-with-resources语句确保输出流被正确关闭
        try (OutputStream os = outputMessage.getBody()) {
            this.objectMapper.writeValue(os, methodReturnValue);
        } // end try-with-resources

    }
}

增加HttpMessageConverter组件,专门负责把对象写出为yaml格式

@Configuration // 表示这是一个配置类
public class MyConfig implements WebMvcConfigurer {

    /**
     * 配置消息转换器,用于支持将对象转换为YAML格式的消息。
     * 
     * @param converters 用于存储消息转换器的列表,这个列表允许Web应用程序处理不同的数据格式。
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 向消息转换器列表中添加一个自定义的YAML消息转换器
        converters.add(new MyYamlHttpMessageConverter());
    }
}

测试
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到