【发布时间】:2021-04-17 17:07:01
【问题描述】:
首先我读过这篇文章:
Spring boot - setting default Content-type header if it's not present in request
旧版本在 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" 默认为 json,虽然 XML 是默认的
来自我在下面发布的评论
问题在于旧版本的 spring 我们可以发送一个接受标头并获取默认为 XML 的请求。但是仍然支持 JSON。
因此,当一个接受头以相同的特性支持 JSON 和 XML 时,我们需要返回 XML。
【问题讨论】:
标签: java spring-boot spring-mvc content-negotiation