SoFunction
Updated on 2025-04-13

How to solve the problem of garbled response in Spring MVC

Spring MVC's latest response solution

Previous solutions

    <!--Enable Packet Scan-->
    <context:component-scan base-package=""/>

    <!--Release static files-->
    <mvc:default-servlet-handler/>
     <!--OpenSpringMVCAnnotation development and solve garbled problems-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="">
                <property name="supportedMediaTypes">
                    <list>
                    <!--ByStringHttpMessageConverterClassicListDo add,Modify the encoding of the response-->
                        <value>text/plain;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

This is a more general method

But it has a disadvantage, that is, it is more troublesome to add one data in response to it. And in previous versions the default response type wastext/html;charset=ISO-8859-1, and it is modified by the final keyword and cannot be modified.

However, in the version after 5.2., you can see by reading the source code:

StringHttpMessageConverterParent classAbstractHttpMessageConverter<T>There is a line of code like this:

public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConverter<T> {
	.....
	@Nullable
	private Charset defaultCharset;
	.....

Although its default encoding set isISO-8859-1, but it is no longer modified by final, which means we can inject it directly into the Spring configuration file and modify the default encoding set of Spring http response.

The code is as follows:

    &lt;!--Solve garbled problems--&gt;
    &lt;mvc:annotation-driven&gt;
        &lt;mvc:message-converters&gt;
            &lt;bean class=""&gt;
                &lt;property name="defaultCharset"&gt;
                    &lt;value&gt;UTF-8&lt;/value&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
        &lt;/mvc:message-converters&gt;

This method is more concise and efficient, and through this method we do not need to worry about the encoding set errors passing through the backend when processing responses in the front-end code.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.