因爲項目須要,同一接口支持根據參數不一樣返回XML和Json兩種格式的數據,在網上看了不少大可能是加後綴的方式來實現返回不一樣格式數據的,後來看了一篇http://www.importnew.com/27632.html 挺不錯,並且講解的很細緻html
(一) 返回不一樣格式的幾種方式git
1) 改變請求後綴的方式改變返回格式github
http://localhost:8080/login.xmlspring
http://localhost:8080/login.jsonjson
2) 以參數的方式要求返回不一樣的格式mvc
http://localhost:8080/login?format=jsonapp
http://localhost:8080/login?format=xmlide
3) 直接在修改controller中每一個接口的請求頭,這種方式是指定該接口返回什麼格式的數據spa
返回XMLcode
@GetMapping(value = "/findByUsername",produces = { "application/xml;charset=UTF-8" })
返回Json
@GetMapping(value = "/findByUsername",produces = { "application/json;charset=UTF-8" })
(二) 使用 1 、 2 兩種方式
主要就只有一個配置
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(true) //是否支持後綴的方式 .favorParameter(true) //是否支持請求參數的方式 .parameterName("format") //請求參數名 .defaultContentType(MediaType.APPLICATION_ATOM_XML); //默認返回格式 } }
有了這個配置以後,基本上第一種第二種都實現了,請求的時候json沒有問題,可是XML返回是空的,沒有任何返回,這是由於你項目中沒有xml的解析,
在pom.xml中加上
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
而後完美解決
方案一
方案二
(三) 第三種,指定返回格式
@GetMapping(value = "/findByUsername",produces = { "application/xml;charset=UTF-8" }) public ResponseResult findByUsername(String username){ if ("admin".equals(username)){ User user = new User(); user.setUsername(username); user.setCity("中國"); user.setSex("女"); return new ResponseResult().setData(user); }else { return new ResponseResult("000000"); } }
這個主要就是修改mapping註解中的produces = { "application/xml;charset=UTF-8" }
可是切記,第三種方式和前兩種方式不能同時存在,當你加入了配置以後再使用第三種方式會致使找不到這個路徑,因此你本身看吧
(四) 在SpringBoot中在yml中配置
spring: mvc: contentnegotiation: #favor-path-extension: true #這個配置了可是不能使用,具體緣由未知,這裏就直接註釋了 favor-parameter: true parameter-name: Format
使用這個配置的方式能夠不用寫代碼了,可是在靈活性上要稍微差一點,可是若是你追求簡潔,這種方式又剛好能知足你的需求,這也是個不錯的選擇
https://github.com/SunArmy/result 這是在寫的時候一邊寫博客一邊寫Demo