The Use of messageConverter in Spring MVC

Keywords: JSON Spring Attribute Apache

Solving String HttpMessageConverter Scrambling Problem

  1. Question:

    When we send string objects back to the browser through spring mvc, because the default decoding set in String HttpMessageConverter message converter is ISO-8859-1; because when the browser receives it, it is scrambled.

  2. Solve:

    Through the configuration file, the problem can be solved:

<mvc:annotation-driven>
    <! -- register-defaults= "true" sets the bean created by our configuration file to the default, and spring MVC will no longer be created in the background - >
    <! - Attribute Interpretation:
        1.register-defaults=true: Tell Springmvc to use the objects created by our configuration file and not create them by itself (the framework creates itself, using the default character set by parametric construction)
        2.index="0" value="UTF-8": The defaultCharset property is configured and set to UTF-8
     -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" value="UTF-8"></constructor-arg>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

Rewrite Mapping Jackson 2HttpMessageConverter

  • analysis

    The function of this message converter is: spring MVC converts objects into JSON format string output

  • problem

    In special cases, if we need to extend the returned string format

  • Solution

    Write a custom class, inherit the converter, rewrite the writeInternal (Object object, HttpOutputMessage output Message) method, and finally replace the message converter with our custom one through the configuration file:

  • Step 1: Customize classes

package com.taotao.springmvc.json;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * MappingJackson2HttpMessageConverter Converting the returned String into a JSON object
 * @author XSOOY
 *
 */
public class CallbackMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    // Make a jsonp support tag and add this parameter to the request parameter
    private String callbackName;

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // Get the current Request object from threadLocal
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String callbackParam = request.getParameter(callbackName);
        if(StringUtils.isEmpty(callbackParam)){
            // The callback parameter was not found and the json data was returned directly
            super.writeInternal(object, outputMessage);
        }else{
            JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
            try {
            /*Extending the string that needs to be returned,
                super.getObjectMapper()Get the ObjectMapper object, which functions as
                Object to json format
                After extension: "method name (json format string object);"
            */
                String result =callbackParam+"("+super.getObjectMapper().writeValueAsString(object)+");";
            //After expansion, it returns to browser through stream
                IOUtils.write(result, outputMessage.getBody(),encoding.getJavaName());
            }
            catch (JsonProcessingException ex) {
                throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
            }
        }

    }

    public String getCallbackName() {
        return callbackName;
    }

    public void setCallbackName(String callbackName) {
        this.callbackName = callbackName;
    }

}
  • Step 2: Configuration files
<mvc:annotation-driven>
    <! -- register-defaults= "true" sets the bean created by our configuration file to the default, and spring MVC will no longer be created in the background - >
    <!--
    CallbackMapping Jackson 2HttpMessageConverter inherits the Mapping Jackson 2HttpMessageConverter class
        WritteInternal () method is rewritten to enhance the function of turning json, such as: xxx programming: callback (xxxx);

    Attribute Interpretation:
        name="callbackName" value="callback": Define the method name of the callback function and define it according to the method name determined by the front end
     -->
        <mvc:message-converters register-defaults="true">
            <bean class="com.taotao.springmvc.json.CallbackMappingJackson2HttpMessageConverter">
                <property name="callbackName" value="callback"></property>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

Posted by Alex C on Sun, 24 Mar 2019 16:06:28 -0700