首页 > 解决方案 > 如何配置spring boot 2默认返回xml?

问题描述

首先,我读过这个:

Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头

旧版本适用于 Spring Boot 1。但是,当接收带有以下接受标头的请求时Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"

响应是 json。

我已经上课了

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_XML);
    }

}

我可以看到正在设置 defaultContentType 策略。但是它被 AcceptHeaderConfig 策略覆盖。

看起来 defaultContentType 仅用作后备。

请注意,spring boot 1 中的相同代码有效并且默认为 XML。


完整示例

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlRootElement;

@SpringBootApplication
@RestController
public class CnApp {

    @RequestMapping("/")
    public Person person(HttpServletRequest request, ModelMap model){
        return new Person();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(CnApp.class, args);
    }

    @XmlRootElement
    public static class Person {
        public String firstName = "Jon";
        public String lastName = "Doe";
    }

    @Configuration
    public static class ServerConfig implements WebMvcConfigurer {
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.defaultContentType(MediaType.APPLICATION_XML);
        }

    }

}

正如您通过运行所看到的, curl localhost:8080 -H"Accept: text/html, image/gif, image/jpg;q=0.2, */*;q=0.2"即使 XML 是默认值,它也默认为 json


从我在下面发布的评论中

问题在于旧版本的 spring 我们可以发送一个接受标头并获取默认为 XML 的请求。但是仍然支持 JSON。

因此,当一个接受头以相同的特性同时支持 JSON 和 XML 时,我们需要返回 XML。

标签: javaspring-bootspring-mvccontent-negotiation

解决方案


您的WebMvc配置与您配置的一样正常。

ContentType如果没有Accept标题,则使用默认值。

要达到您的范围,您必须继续使用内容协商策略,并禁用 Accept 标头。您的configureContentNegotiation方法应如下所示:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false)
    .parameterName("mediaType")
    .ignoreAcceptHeader(true)
    .useJaf(false)
    .defaultContentType(MediaType.APPLICATION_XML)
    .mediaType("xml", MediaType.APPLICATION_XML;
}

您可以查看Spring 博客上的这篇文章和 Baeldung上的这篇文章。


推荐阅读