Spring mvc returns garbled characters and method return types

Writing code today has a method that returns a garbled value


Such garbled characters were very strange at the time. They were all set to utf-8. Why are they garbled characters? Look at postman, and the returned value is in the header of the headers.

There is a content-Type property where the value is    text/plain;charset=ISO-8859-1

The reason for the garbled characters here is obvious. My utf-8 encoding format is decoded with iso-8859, and it is obvious that there will be garbled characters.

Then I was thinking about why the browser will use the iso encoding format to decode.


The value returned here is spring, and I did not find the contentType attribute in httpservletrequest, which means that this value is not determined by the browser.

When I change the return value to Map<String, String> without using spring, there is no garbled code, it's amazing



My understanding at the time was that it might be right to use spring's map to convert json, but I decided to debug to see if that was the case.

There are such classes in springmvc

AbstractMessageConverterMethodProcessor


This method is used to set the corresponding encoding format

this.getProducibleMediaTypes(servletRequest, returnValueClass);


This method will traverse the compiler (I used to think that there is only one StringHttpMessageConverter ). There are originally seven. The method canWrite here will compare which compiler HttpMessageConverter can use according to your return type such as String HashMap.

The compilers that can be used in the String type have 4 converters. The above method will sort and select the first one to use its encoding type. The String class is unfortunately the first one is iso. There are only two corresponding to Map, both of which are utf -8. So the reason why the value returned by map will not be garbled here is found.

Group photo of seven compilers



Of course, we can use utf-8 instead of his default encoding format, just configure it in spring


In this way, even if the type of the returned value is string, the encoding format is correct. I have to admire these people who wrote spring here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324604017&siteId=291194637