spring boot--内容协商

内容协商

内容协商机制是指服务器根据客户端的请求来决定返回资源的表现形式,由springmvc提供。

就是客户端要什么样的格式,客户端就返回什么样的格式。比如json或者xml。

实现内容协商的两种方式

  1. 通过HTTP请求头(如accept)
  2. 通过请求参数如:format

指定客户端接收的数据类型。

通过HTTP请求头(如accept)

响应json格式

// 默认响应json字符串
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/detail")
    public User detail(){
        return userService.getUserById();
    }
}

响应xml

先引入依赖

<!--        可以将Java对象转换成xml格式的字符串-->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

实体类代码

@Data
@NoArgsConstructor
// 将Java对象转换成xml格式的字符串
@JacksonXmlRootElement
public class User {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

不用修改controller。这样就会根据客户端请求的accept来返回对应格式的数据。

通过请求参数如:format

请求地址:http://localhost:8080/detail?format=json。如果优先考虑使用format方式,需要以下配置

# 内容协商时,优先考虑请求参数format方式,参数名必须是format
spring.mvc.contentnegotiation.favor-parameter=true
# 配置format参数的名称为type,那么请求路径就是http://localhost:8080/detail?type=json
spring.mvc.contentnegotiation.parameter-name=type

消息转换器

请求时通过哪些条件确定使用哪个消息转换器

springmvc会检查请求的content-type。以确定请求体的消息格式。

响应时通过哪些条件确定使用哪个消息转换器

springmvc会检查请求的accept。以确定请求体的消息格式。

定义自己的HTTPMessageConverter

1.引入处理yaml的依赖

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

2.新增一种媒体类型yaml

配置如下

# 新增一种媒体类型yaml
# 媒体类型的名字可以自定义
# 媒体类型的名字是yaml  媒体类型的值是text/yaml
spring.mvc.contentnegotiation.media-types.yaml=text/yaml

3.自定义HttpMessageConverter

// 专门处理yaml数据的消息转换器
// 所有的消息转换器必须实现HttpMessageConverter接口,或者继承AbstrcatHttpMessageConverter抽象类
public class YamlHttpMessageConverter extends AbstractHttpMessageConverter {

    // 对象映射器
    private ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAML.Feature.WRITE_DOC_START_MARKER));

    // 将媒体类型text/yaml和application/x-yaml与此消息转换器关联起来
    public YamlHttpMessageConverter() {
        super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
    }

    // 指定此消息转换器适合哪些类型的对象
    @Override
    protected boolean supports(Class clazz) {
        // 只有User对象才能使用此消息转换器
        return User.class.isAssignableFrom(clazz);
    }

    // 将yaml格式字符串转换成Java对象
    // @RequestBody
    @Override
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    // 将Java对象转换成yaml格式字符串
    // @ResponseBody
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        objectMapper.writeValue(outputMessage.getBody(), o);
    }
}

4.配置消息转换器

// 添加这个注解后,表示不再使用springboot提供的默认配置
// @EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

//    将新的消息转换器进行配置
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new YamlHttpMessageConverter());
    }
}
posted @ 2026-01-27 14:25  NE_STOP  阅读(0)  评论(0)    收藏  举报