For text resources in the SpringBoot static directory, if they contain Chinese, the Chinese in the content will be garbled when accessed directly through the browser. This is despite the fact that the files themselves are UTF8 encoded.

Demo

Prepare a static resource file - foo.js

springboot static file

The content of the file contains Chinese

1
2
3
4
5
/*
    SpringBoot中文社区
 */
 
console.log('https://springboot.io');

Direct access via browser, Chinese appears garbled

Spring Boot garbled

The reason for this is that the encoding of content is not specified in ContentType.

Solution

I tried to find the spring configuration to solve this problem, but couldn’t find it. Finally I found that the Undertow server provides the MimeMapping interface. That means that it is possible to customize the contentType for different types of files.

Then we just need to add the encoding after the ContentType of the default text file type and it’s OK.

UndertowConfiguration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.context.annotation.Configuration;

import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.MimeMapping;

/**
 * 
 * Undertow 服务器配置
 * 
 * @author KevinBlandy
 *
 */
@Configuration
public class UndertowConfiguration implements UndertowDeploymentInfoCustomizer {

    @Override
    public void customize(DeploymentInfo deploymentInfo) {

        /**
            * 覆盖默认文本类型的字符ContentType, 添加UTF8编码
            * 
            * @see io.undertow.util.MimeMappings
            */
        deploymentInfo.addMimeMapping(new MimeMapping("html", "text/html; charset=utf-8"));
        deploymentInfo.addMimeMapping(new MimeMapping("htm", "text/html; charset=utf-8"));
        deploymentInfo.addMimeMapping(new MimeMapping("css", "text/css; charset=utf-8"));
        deploymentInfo.addMimeMapping(new MimeMapping("js", "application/javascript; charset=utf-8"));
        deploymentInfo.addMimeMapping(new MimeMapping("json", "application/json; charset=utf-8"));
        deploymentInfo.addMimeMapping(new MimeMapping("md", "text/markdown; charset=utf-8"));
    }
}

After adding the configuration class, restart the application. Accessing the resource file, Chinese has been displayed normally.

spring static file

Reference https://springboot.io/t/topic/4831