編碼算不上一個大問題,即使你什么都不管,也有很大的可能你不會遇到任何問題,因為大部分框架都有默認的編碼配置,有很多是UTF-8,那么遇到中文亂碼的機會很低,所以很多人也忽視了。
Spring系列產品大量運用在網站開發中,而Spring Boot是為了簡化配置而出現的,理論上講Spring Boot應該默認配置UTF-8為默認編碼,但是網絡上依然可以看到很多關於Spring Boot亂碼的文章,大部分解決方案沿用Spring MVC的方案,自定義EncodingFilter。
但是仔細查看Spring Boot的文檔,可以看到默認的編碼的確是UTF-8
1
2
|
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.
spring.http.encoding.enabled=true # Enable http encoding support.
|
而相關的配置會在HttpEncodingAutoConfiguration中使用
1
2
3
4
5
6
7
8
9
|
@Bean
@ConditionalOnMissingBean(CharacterEncodingFilter.class)
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
return filter;
}
|
而這里你其實可以看到,默認情況下forceRequestEncoding和forceResponseEncoding是為false的。
在配置中自己加上一行
1
|
spring.http.encoding.force=true
|
除了常見的http encoding,Spring Boot中還可以控制這些編碼
1
2
3
4
5
6
|
banner.charset
spring.freemarker.charset
server.tomcat.uri-encoding
spring.mail.default-encoding
spring.messages.encoding
spring.thymeleaf.encoding
|
只不過這些值默認就設置為UTF-8,而且並需要搭配其他配置開關使用,所以一般不需要管。