java - 如何配置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。
解决方案
您的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;
}
推荐阅读
- vba - 如何在 Excel 中从 vba 连接到 ms-access 数据库?
- spring - 带有用户名和密码的 Zonky + Spring Boot + Postgres + Flyway
- jquery - 如何在所有类中从 YYYY-MM-DD 转换为 DD-MM-YYYY,每个类在 jquery 中具有不同的值?
- javascript - 使用 identityserver4 和 aspnet 身份时如何安全地实现空闲超时?
- python - 如何比较子列表的值
- java - 无法更改预定义的字符串值
- r - R中多边形的交集使用sf
- node.js - 如何有效地发送大数据包/合并较小的数据包?
- python - 如何将方程绘制到具有重新定义索引的数组中
- php - php mysql select函数返回0但没有错误