springmvc-内容协商

springmvc-内容协商

起男 445 2022-02-28

springmvc-内容协商

springmvc提供了一种被称作内容协商的机制,客户端在请求时说明需要的mime类型,服务端只需要一些策略就可以实现一个接口返回不同的mime类型的数据格式

依赖

如果需要返回xml的类型需要导入

<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
	<version>2.11.4</version>
</dependency>

配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorParameter(true)
                .parameterName("format")//标识参数名称
                .defaultContentType(MediaType.APPLICATION_JSON)//默认使用类型
                .mediaType("xml",MediaType.APPLICATION_XML)
                .mediaType("json",MediaType.APPLICATION_JSON);
    }
}

接口

@GetMapping(value = "deni",produces = {"application/json","application/xml"})
    public Map<String,String> demo(String name){
        Map<String,String> map = new HashMap<>();
        map.put("name",name);
        map.put("age","20");
        return map;
    }

测试

发起请求:http://localhost:8080/demo?name=aaa&format=xml或http://localhost:8080/demo?name=aaa&format=json