-
Notifications
You must be signed in to change notification settings - Fork 141
RequestMapping的produces参数
gexiangdong edited this page May 6, 2018
·
6 revisions
produces参数指明方法可返回给客户端的内容格式,spring会去和request头的Accept部分比较,如果发现相符合,则把方法返回值转换成相符合的格式(例如json, xml等),如果没有符合的,则返回406
RestController的方法上这么写
@PostMapping(consumes = {MediaType.TEXT_XML_VALUE},
produces = {MediaType.TEXT_XML_VALUE})用下面的命令测试没问题,因为Accept和上面的相符合,会返回xml
curl -v \
-d '<TvSeriesDto><id>1</id><name>West Wrold</name><originRelease>2016-10-02</originRelease></TvSeriesDto>' \
-X POST -H 'Content-type:text/xml' \
-H 'Accept:text/xml' \
http://localhost:8080/tvseries如果用下面的命令,则会返回406, Could not find acceptable representation。因为accept不和方法注解相符合
curl -v \
-d '<TvSeriesDto><id>1</id><name>West Wrold</name><originRelease>2016-10-02</originRelease></TvSeriesDto>' \
-X POST -H 'Content-type:text/xml' \
-H 'Accept:application/xml' \
http://localhost:8080/tvseries可以通过配置,修改默认的格式
@Configuration
public class WebAppConfigurer extends WebMvcConfigurationSupport {
@Override
protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// 这里设置默认的返回格式
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}