溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring接口通過(guò)配置支持返回多種格式(xml,json,html,excel)

發(fā)布時(shí)間:2020-10-09 10:56:32 來(lái)源:腳本之家 閱讀:282 作者:Jekyll 欄目:編程語(yǔ)言

1. 簡(jiǎn)介

本文主要給大家介紹使用SpringMVC的后端服務(wù)如何通過(guò)配置來(lái)支持多種返回值類(lèi)型(xml,json,html,excel)

這里的代碼使用的是springboot,下載地址:https://github.com/xiagn825/springboot-todolist/tree/springboot-ContentNegotiation

2. 基礎(chǔ)概念

2.1 HttpHeader中Content-Type和Accept設(shè)置的區(qū)別

Accept:接口要返回給客戶端的數(shù)據(jù)格式

 curl --header 'Accept:application/json' http://localhost:8080/todo

Content-Type:客戶端發(fā)送給服務(wù)器端的數(shù)據(jù)格式

 curl -X PUT --header 'Content-Type:application/json' -d '{"title":"周末日程","content":"睡覺(jué)"}' http://localhost:8080/todo

2.2 SpringMVC生成輸出的兩種方式

1) 當(dāng)服務(wù)端使用Restful的方式,只為客戶端的ajax或其他服務(wù)端請(qǐng)求提供數(shù)據(jù)時(shí),通常會(huì)使用@ResponseBody來(lái)標(biāo)識(shí)你的返回,這時(shí)候Spring使用HttpMessageConverter來(lái)把返回的對(duì)象格式化成所需的格式。

2) 當(dāng)你需要提供表現(xiàn)層(比如:HTML),這時(shí)候SpringMVC使用ViewResolver來(lái)將處理你的返回。

有時(shí)候你的應(yīng)用程序這兩者都要提供

2.3 SpringMVC輸出格式判定

很多時(shí)候?yàn)榱酥С侄鄠€(gè)系統(tǒng)或多個(gè)終端,你需要讓相同的數(shù)據(jù)已不同的表現(xiàn)形式輸出。

SpringMVC使用ContentNegotationStrategy來(lái)判定用戶請(qǐng)求希望得到什么格式的數(shù)據(jù)。

ContentNegotationStrategy通過(guò)三種方式來(lái)識(shí)別用戶想要返回什么樣的數(shù)據(jù)

  • 通過(guò)請(qǐng)求URL后綴:http://myserver/myapp/accounts/list.html 返回html格式
  • 通過(guò)請(qǐng)求的參數(shù):http://myserver/myapp/accounts/list?format=xls 該設(shè)置默認(rèn)不開(kāi)啟,默認(rèn)key是format。
  • 通過(guò)HTTP Header的Accept:Accept:application/xml 優(yōu)先級(jí)由上至下

請(qǐng)看如下配置

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
 configurer.favorPathExtension(false)
   .favorParameter(true)
   .parameterName("mediaType")
   .defaultContentType(MediaType.APPLICATION_JSON)
   .mediaType("xml", MediaType.APPLICATION_XML)
   .mediaType("html", MediaType.TEXT_HTML)
   .mediaType("json", MediaType.APPLICATION_JSON);
}

在你工程的WebMvcConfig中加入以上配置,表示關(guān)閉URL后綴的規(guī)則,打開(kāi)請(qǐng)求參數(shù)規(guī)則并設(shè)置請(qǐng)求參數(shù)為'mediaType',默認(rèn)的返回格式是json,還支持返回xml,html。

這三個(gè)組件是用來(lái)處理返回不同格式輸出的關(guān)鍵

  • Request Mappings: 決定不同的請(qǐng)求到不同的方法并返回不同的格式.
  • View Resolution: 根據(jù)類(lèi)型返回合適的表示層.
  • HttpMessageConverters: 將request中的參數(shù)轉(zhuǎn)換成java對(duì)象,將java對(duì)象轉(zhuǎn)換成相應(yīng)的輸出格式到response.

2.4 RequestMappings

2.4.1 RequestMappingHandlerMapping

我們?cè)趕pring中通常使用的就是RequestMappingHandlerMapping,根據(jù)RequestMappingInfo,細(xì)化匹配條件,整體的查找過(guò)程如下:

AbstractHandlerMethodMapping實(shí)現(xiàn)接口getHandlerInternal

  1. 使用UrlPathHelper查找request對(duì)應(yīng)的path

  2. 查找path對(duì)應(yīng)的HandlerMethod

    2.1 從urlMap中直接等值匹配查找匹配條件RequestMappingInfo

    2.2 如果等值查找到匹配條件,將其添加到match條件中

    2.3 如果沒(méi)有找到匹配條件,使用所有的handlerMethod的RequestMappingInfo進(jìn)行匹配

    2.4 對(duì)匹配到的Match進(jìn)行排序,取出最高優(yōu)先級(jí)的Match,并核對(duì)是否是唯一的最高優(yōu)先級(jí)

    2.5 對(duì)匹配到條件,沒(méi)有匹配到條件的兩種情況,分別進(jìn)行封裝

  3. 封裝HandlerMethod,確保bean中存的是實(shí)例    ContentNegotiationManager其中提供了針對(duì)miniType的match條件比較,使框架可以匹配到最合適的處理方法。

2.5 HttpMessageConverter

2.5.1 The Default Message Converters

SpringMvc默認(rèn)會(huì)加載下列HttpMessageConverters:

ByteArrayHttpMessageConverter – converts byte arrays
StringHttpMessageConverter – converts Strings
ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
SourceHttpMessageConverter – converts javax.xml.transform.Source
FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)
MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)

我們?nèi)绻祷氐氖鞘褂聾ResponseBody來(lái)標(biāo)識(shí)的,那么框架會(huì)使用HttpMessageConverter來(lái)處理返回值,默認(rèn)的xmlCoverter不是特別好用,依賴返回實(shí)體對(duì)象上的@XmlRootElement注解,不是很方便所以引入輔助類(lèi)庫(kù),并自定義MessageConverter這樣可以直接將返回的對(duì)象處理成xml格式。

Gradle import library

compile group: 'org.springframework', name: 'spring-oxm', version: '4.3.9.RELEASE'
compile group: 'com.thoughtworks.xstream', name: 'xstream', version: '1.4.10'

configuration

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 converters.add(createXmlHttpMessageConverter());
 super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
 MarshallingHttpMessageConverter xmlConverter =
   new MarshallingHttpMessageConverter();
 XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
 xmlConverter.setMarshaller(xstreamMarshaller);
 xmlConverter.setUnmarshaller(xstreamMarshaller);
 return xmlConverter;
}

2.6 View Resolution

2.6.1 頁(yè)面render(freemarker)

當(dāng)需要返回頁(yè)面時(shí)就需要由合適的viewResolver來(lái)繪制畫(huà)面,這里采用freemarker作為頁(yè)面引擎。

Gradle import library

compile("org.springframework.boot:spring-boot-starter-freemarker")

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI