Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Spring interface supports methods that return multiple formats

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "Spring interface supports the method of returning multiple formats". In the operation of actual cases, many people will encounter this dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Brief introduction

This article describes how back-end services using SpringMVC can be configured to support multiple return value types (xml,json,html,excel)

two。 Basic concept

2.1 differences between Content-Type and Accept settings in HttpHeader

Accept: the data format to be returned by the API to the client

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

Content-Type: the data format that the client sends to the server

1curl-X PUT-- header 'Content-Type:application/json'-d' {"title": "weekend schedule", "content": "sleep"} 'http://localhost:8080/todo

2.2 two ways for SpringMVC to generate output

1) when the server uses Restful to provide data only for client ajax or other server requests, @ ResponseBody is usually used to identify your return. In this case, Spring uses HttpMessageConverter to format the returned object into the desired format.

2) when you need to provide a presentation layer (for example, HTML), SpringMVC uses ViewResolver to process your return.

Sometimes your application has to provide both

2.3 SpringMVC output format determination

In many cases, in order to support multiple systems or terminals, you need to output the same data in different forms.

SpringMVC uses ContentNegotationStrategy to determine what format of data a user requests.

ContentNegotationStrategy identifies what kind of data users want to return in three ways.

Return the html format by requesting the URL suffix: http://myserver/myapp/accounts/list.html

The requested parameter: http://myserver/myapp/accounts/list?format=xls. This setting is not enabled by default, and the default key is format.

Accept:Accept:application/xml priority through HTTP Header from top to bottom

Please see the following configuration

@ 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)

}

Add the above configuration to the WebMvcConfig of your project to disable the URL suffix rule, open the request parameter rule and set the request parameter to 'mediaType',. The default return format is json, and xml,html is also supported.

These three components are the key to dealing with returning output in different formats

Request Mappings: determine different requests to different methods and return different formats.

View Resolution: returns the appropriate presentation layer based on the type.

HttpMessageConverters: convert the parameters in request to java objects, and convert java objects to the corresponding output format to response.

2.4 RequestMappings

2.4.1 RequestMappingHandlerMapping

We usually use RequestMappingHandlerMapping in spring. According to RequestMappingInfo, we refine the matching conditions. The overall search process is as follows:

AbstractHandlerMethodMapping implements interface getHandlerInternal

1. Use UrlPathHelper to find the path corresponding to request

two。 Find the HandlerMethod corresponding to path

2.1 find matching condition RequestMappingInfo from urlMap by direct equivalent matching

2.2 if a matching condition is found by equivalence, add it to the match condition

2.3 if no matching condition is found, match using all handlerMethod's RequestMappingInfo

2.4 sort the matched Match, take out the highest priority Match, and check whether it is the only highest priority

2.5 encapsulate the two cases that match to the condition and not match to the condition

3. Encapsulate HandlerMethod to ensure that instance ContentNegotiationManager is stored in bean, which provides match condition comparison for miniType, so that the framework can match to the most appropriate processing method.

2.5 HttpMessageConverter

2.5.1 The Default Message Converters

SpringMvc loads the following HttpMessageConverters by default:

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.

Jaxb2RootElementHttpMessageConverter-converts Java objects to/from XML (added only if JAXB2 is present on the classpath)

MappingJackson2HttpMessageConverter-converts JSON (added only if Jackson2 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)

If what we return is identified by @ ResponseBody, then the framework will use HttpMessageConverter to process the return value. The default xmlCoverter is not very easy to use, and it is not very convenient to rely on the @ XmlRootElement annotation on the returned entity object, so it is not very convenient to introduce auxiliary class libraries and customize MessageConverter so that the returned objects can be directly processed into xml format.

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report