当前位置: 移动技术网 > IT编程>开发语言>Java > spring接口通过配置支持返回多种格式(xml,json,html,excel)

spring接口通过配置支持返回多种格式(xml,json,html,excel)

2019年07月19日  | 移动技术网IT编程  | 我要评论

1. 简介

本文主要给大家介绍使用springmvc的后端服务如何通过配置来支持多种返回值类型(xml,json,html,excel)

这里的代码使用的是springboot,下载地址:https://github.com/xiagn825/springboot-todolist/tree/springboot-contentnegotiation

2. 基础概念

2.1 httpheader中content-type和accept设置的区别

accept:接口要返回给客户端的数据格式

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

content-type:客户端发送给服务器端的数据格式

 curl -x put --header 'content-type:application/json' -d '{"title":"周末日程","content":"睡觉"}' http://localhost:8080/todo

2.2 springmvc生成输出的两种方式

1) 当服务端使用restful的方式,只为客户端的ajax或其他服务端请求提供数据时,通常会使用@responsebody来标识你的返回,这时候spring使用httpmessageconverter来把返回的对象格式化成所需的格式。

2) 当你需要提供表现层(比如:html),这时候springmvc使用viewresolver来将处理你的返回。

有时候你的应用程序这两者都要提供

2.3 springmvc输出格式判定

很多时候为了支持多个系统或多个终端,你需要让相同的数据已不同的表现形式输出。

springmvc使用contentnegotationstrategy来判定用户请求希望得到什么格式的数据。

contentnegotationstrategy通过三种方式来识别用户想要返回什么样的数据

  • 通过请求url后缀:http://myserver/myapp/accounts/list.html 返回html格式
  • 通过请求的参数:http://myserver/myapp/accounts/list?format=xls 该设置默认不开启,默认key是format。
  • 通过http header的accept:accept:application/xml 优先级由上至下

请看如下配置

@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中加入以上配置,表示关闭url后缀的规则,打开请求参数规则并设置请求参数为'mediatype',默认的返回格式是json,还支持返回xml,html。

这三个组件是用来处理返回不同格式输出的关键

  • request mappings: 决定不同的请求到不同的方法并返回不同的格式.
  • view resolution: 根据类型返回合适的表示层.
  • httpmessageconverters: 将request中的参数转换成java对象,将java对象转换成相应的输出格式到response.

2.4 requestmappings

2.4.1 requestmappinghandlermapping

我们在spring中通常使用的就是requestmappinghandlermapping,根据requestmappinginfo,细化匹配条件,整体的查找过程如下:

abstracthandlermethodmapping实现接口gethandlerinternal

  1. 使用urlpathhelper查找request对应的path

  2. 查找path对应的handlermethod

    2.1 从urlmap中直接等值匹配查找匹配条件requestmappinginfo

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

    2.3 如果没有找到匹配条件,使用所有的handlermethod的requestmappinginfo进行匹配

    2.4 对匹配到的match进行排序,取出最高优先级的match,并核对是否是唯一的最高优先级

    2.5 对匹配到条件,没有匹配到条件的两种情况,分别进行封装

  3. 封装handlermethod,确保bean中存的是实例    contentnegotiationmanager其中提供了针对minitype的match条件比较,使框架可以匹配到最合适的处理方法。

2.5 httpmessageconverter

2.5.1 the default message converters

springmvc默认会加载下列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)

我们如果返回的是使用@responsebody来标识的,那么框架会使用httpmessageconverter来处理返回值,默认的xmlcoverter不是特别好用,依赖返回实体对象上的@xmlrootelement注解,不是很方便所以引入辅助类库,并自定义messageconverter这样可以直接将返回的对象处理成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 页面render(freemarker)

当需要返回页面时就需要由合适的viewresolver来绘制画面,这里采用freemarker作为页面引擎。

gradle import library

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网