1. Introduction
This article mainly introduces how to use SpringMVC backend services to support multiple return value types (xml, json, html, excel) through configuration.
The code here uses springboot, download address: https://github.com/xiagn825/springboot-todolist/tree/springboot-ContentNegotiation
2. Basic concepts
2.1 The difference between Content-Type and Accept settings in HttpHeader
Accept: The data format to be returned to the client by the interface
curl --header 'Accept:application/json' http://localhost:8080/todo
Content-Type: The data format sent by the client to the server
curl -X PUT --header 'Content-Type:application/json' -d '{"title":"weekend schedule","content":"sleep"}' http://localhost:8080/todo2.2 Two ways to generate output in SpringMVC
1) When the server uses Restful method to only provide data for the client's ajax or other server requests, @ResponseBody is usually used to identify your return. At this time, Spring uses HttpMessageConverter to format the returned object into the required format.
2) When you need to provide a presentation layer (such as HTML), SpringMVC uses ViewResolver to process your return.
Sometimes your application has to provide both
2.3 SpringMVC output format determination
Many times, in order to support multiple systems or multiple terminals, you need to output the same data in different manifestations.
SpringMVC uses ContentNegotationStrategy to determine what format of data the user requests to obtain.
ContentNegotationStrategy uses three ways to identify what kind of data the user wants to return
Please see the configuration below
@Overridepublic void configureContentNegotiation(ContentNegotiationConfigurer configure) { 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, which means closing the rule of URL suffix, opening the request parameter rule and setting the request parameter to 'mediaType'. The default return format is json, and it also supports returning xml and html.
These three components are the key to returning outputs in different formats
2.4 RequestMappings
2.4.1 RequestMappingHandlerMapping
What we usually use in spring is RequestMappingHandlerMapping. According to RequestMappingInfo, we refine the matching conditions. The overall search process is as follows:
AbstractHandlerMethodMapping implementation interface getHandlerInternal
1. Use UrlPathHelper to find the path corresponding to the request
2. Find the HandlerMethod corresponding to the path
2.1 Find matching conditions from urlMap RequestMappingInfo
2.2 If the matching condition is found in the equivalent value, add it to the match condition
2.3 If no matching condition is found, use RequestMappingInfo of all handlerMethods to match
2.4 Sort the matches, take out the highest priority Match, and check whether it is the only highest priority
2.5: Encapsulate the two situations where the conditions are matched and the conditions are not matched.
3. Encapsulate HandlerMethod to ensure that the instance of the bean is stored in the ContentNegotiationManager, which provides a comparison of match conditions for miniType, so that the framework can match the most appropriate processing method.
2.5 HttpMessageConverter
2.5.1 The Default Message Converters
SpringMvc will load the following HttpMessageConverters by default:
ByteArrayHttpMessageConverter converts byte arraysStringHttpMessageConverter converts StringsResourceHttpMessageConverter converts org.springframework.core.io.Resource for any type of octet streamSourceHttpMessageConverter converts javax.xml.transform.SourceFormHttpMessageConverter 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)
If we return it is identified by @ResponseBody, the framework will use HttpMessageConverter to process the return value. The default xmlCoverter is not particularly useful and depends on the @XmlRootElement annotation on the entity object. It is not very convenient. Therefore, we introduce the auxiliary class library and customize the MessageConverter so that the returned object can be processed directly into the 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
@Overridepublic 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 Page render (freemarker)
When you need to return to the page, you need to draw the picture by a suitable viewResolver, and here you use freemarker as the page engine.
Gradle import library
compile("org.springframework.boot:spring-boot-starter-freemarker")Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.