Detailed description of the use of Http information converter for custom SpringMVC, springmvc Converter
In SpringMVC, the @ RequestBody and @ ResponseBody annotations can be used to convert the request message to the object and the object to the Response Message respectively. The underlying flexible message conversion mechanism is used. Use HttpMessageConverter, Which is configured by default, to parse the data and bind it to the object to be returned.
HttpInputMessage
This class is SpringMVC's internal abstraction of an Http request message. In the read () method of HttpMessageConverter, There is a form parameter of HttpInputMessage, it is the internal abstraction of the receptor "Request Message" applied by the message converter of SpringMVC. The message converter extracts messages from the "Request Message" according to rules and converts them to objects declared in method parameters.
package org.springframework.http;import java.io.IOException;import java.io.InputStream;public interface HttpInputMessage extends HttpMessage { InputStream getBody() throws IOException;}
HttpOutputMessage
In the write () method of HttpMessageConverter, There is a form parameter of HttpOutputMessage, which is the internal abstraction of the receptor "Response Message" applied by SpringMVC message converter, the message converter writes the "Response Message" to the response message according to certain rules.
package org.springframework.http;import java.io.IOException;import java.io.OutputStream;public interface HttpOutputMessage extends HttpMessage { OutputStream getBody() throws IOException;}
HttpMessageConverter
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.springframework.http.converter;import java.io.IOException;import java.util.List;import org.springframework.http.HttpInputMessage;import org.springframework.http.HttpOutputMessage;import org.springframework.http.MediaType;public interface HttpMessageConverter<T> { boolean canRead(Class<?> clazz, MediaType mediaType); boolean canWrite(Class<?> clazz, MediaType mediaType); List<MediaType> getSupportedMediaTypes(); T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException; void write(T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;}
The HttpMessageConverter interface provides five methods:
- CanRead: determines whether the converter can convert the request content to a Java object.
- CanWrite: determines whether the converter can convert a Java object to the returned content.
- GetSupportedMediaTypes: Obtain the MediaType type supported by this converter
- Read: reads the request content and converts it to a Java object.
- Write: write the returned content after converting the Java object
The parameters of the read and write methods have the HttpInputMessage and HttpOutputMessage objects, which represent the request and response parts of an Http Communication respectively, you can use the getBody method to obtain the corresponding input stream and output stream.
Currently, many converters are provided by default in Spring, including:
| Name |
Function |
Read supports MediaType |
Write support for MediaType |
| ByteArrayHttpMessageConverter |
Mutual conversion between data and byte Arrays |
/ |
Application/octet-stream |
| StringHttpMessageConverter |
Mutual conversion between data and String type |
Text /* |
Text/plain |
| FormHttpMessageConverter |
Form and MultiValueMap <string, string = ""> convert each other |
Application/x-www-form-urlencoded |
Application/x-www-form-urlencoded |
| SourceHttpMessageConverter |
Mutual conversion between data and javax. xml. transform. Source |
Text/xml and application/xml |
Text/xml and application/xml |
| MarshallingHttpMessageConverter |
Use spring‑aller/un‑aller to convert XML data |
Text/xml and application/xml |
Text/xml and application/xml |
| MappingJackson2HttpMessageConverter |
Use Jackson's ObjectMapper to convert Json data |
Application/json |
Application/json |
| MappingJackson2XmlHttpMessageConverter |
Use Jackson's XmlMapper to convert XML data |
Application/xml |
Application/xml |
| BufferedImageHttpMessageConverter |
Conversion between data and java. awt. image. BufferedImage |
All types supported by Java I/O APIs |
All types supported by Java I/O APIs |
HttpMessageConverter matching process:
@ RequestBody: According to the Content-Type of the Request object header, matching the appropriate HttpMessageConverter one by one to read data.
private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType) throws Exception { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName); } throw new HttpMediaTypeNotSupportedException("Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return messageConverter.read(paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
@ ResponseBody: Based on the Accept attribute (separated by commas) of the header part of the Request object, the HttpMessageConverter that can be processed is traversed one by one based on the Type in accept.
private void writeWithMessageConverters(Object returnValue, HttpInputMessage inputMessage, HttpOutputMessage outputMessage) throws IOException, HttpMediaTypeNotAcceptableException { List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept(); if (acceptedMediaTypes.isEmpty()) { acceptedMediaTypes = Collections.singletonList(MediaType.ALL); } MediaType.sortByQualityValue(acceptedMediaTypes); Class<?> returnValueType = returnValue.getClass(); List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (getMessageConverters() != null) { for (MediaType acceptedMediaType : acceptedMediaTypes) { for (HttpMessageConverter messageConverter : getMessageConverters()) { if (messageConverter.canWrite(returnValueType, acceptedMediaType)) { messageConverter.write(returnValue, acceptedMediaType, outputMessage); if (logger.isDebugEnabled()) { MediaType contentType = outputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = acceptedMediaType; } logger.debug("Written [" + returnValue + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } this.responseArgumentUsed = true; return; } } } for (HttpMessageConverter messageConverter : messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); } } throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes); }
Customize a JSON Converter
Class CustomJsonHttpMessageConverter implements HttpMessageConverter {// Jackson's Json ing class private ObjectMapper mapper = new ObjectMapper (); // The type supported by this converter: application/json private List supportedMediaTypes = Arrays. asList (MediaType. APPLICATION_JSON ); /*** determine whether the converter can convert the input content to a Java type * @ param clazz the Java type to be converted * @ param mediaType MediaType of the Request * @ return */@ Override public boolean canRead (Class clazz, mediaType mediaType) {if (mediaType = null) {return true;} for (MediaType supportedMediaType: getSupportedMediaTypes () {if (supportedMediaType. includes (mediaType) {return true ;}} return false ;} /*** determine whether the converter can convert the Java type to the specified output content * @ param clazz the Java type to be converted * @ param mediaType MediaType of the Request * @ return */@ Override public boolean canWrite (Class clazz, mediaType mediaType) {if (mediaType = null | MediaType. ALL. equals (mediaType) {return true;} for (MediaType supportedMediaType: getSupportedMediaTypes () {if (supportedMediaType. includes (mediaType) {return true;} return false;}/*** obtain the MediaType * @ return */@ Override public List getSupportedMediaTypes () supported by this converter () {return supportedMediaTypes;}/*** read the request content, convert Json to a Java Object * @ param clazz the Java type to be converted * @ param inputMessage request Object * @ return * @ throws IOException * @ throws HttpMessageNotReadableException */@ Override public Object read (Class clazz, httpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {return mapper. readValue (inputMessage. getBody (), clazz );} /*** convert a Java object to Json return content * @ param o object to be converted * @ param contentType return type * @ param outputMessage receipt object * @ throws IOException * @ throws HttpMessageNotWritableException * // @ Override public void write (Object o, mediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {mapper. writeValue (outputMessage. getBody (), o );}}
Custom MappingJackson2HttpMessage
From the write method in the abstringjackson2httpmessageconverter parent class AbstractHttpMessageConverter, we can see that this method writes data to the output stream of the returned result through the writeInternal method, so you only need to override this method:
@ Beanpublic implements encryption () {return new MappingJackson2HttpMessageConverter () {// rewrite the writeInternal method. encrypt the content before returning it @ Override protected void writeInternal (Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {// use Jackson's ObjectMapper to convert a Java object to a Json String ObjectMapper mapper = new ObjectMapper (); String json = mapper. writeValueAsString (object); LOGGER. error (json); // encrypted String result = json + "encrypted! "; LOGGER. error (result); // output outputMessage. getBody (). write (result. getBytes ());}};}
After that, you need to configure the custom converter to Spring. Here, you can rewrite the configureMessageConverters method in WebMvcConfigurer to add the custom converter:
// Add a custom converter @ Overridepublic void configureMessageConverters (List
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.