Spring boot 中文乱码

Spring boot 默认编码配置为UTF-8, 但是在没有找到配置的时候会用iso8859-1 编码

Spring boot Response 响应中文乱码, 特别的,你如果在微服务中也会出现这样的问题

解决的方案如下要改变以下四个,找了一上午

经过以下重写能处理 99%的中文乱码问题, 剩下1%靠运气了!

确定数据库表的字符为UTF-8

CREATE TABLE IF NOT EXISTS table_name (
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1;

确定连接mysql时带上编码 UTF8

jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf8&jdbcCompliantTruncation=false&useSSL=false

Spring application.properties 配置为UTF-8

spring.freemarker.setting.number_format=0.##
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.http.encoding.force-response=true
banner.charset=UTF-8
spring.messages.encoding=UTF-8

添加 Sptring StringHttpMessageConverter 为UTF-8 编码

@Configuration
public class WebCodeConfiguration extends WebMvcConfigurationSupport {

	@Override
	protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		for (HttpMessageConverter<?> converter : converters) {
			// 解决controller返回普通文本中文乱码问题
			if (converter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
			}
			// 解决controller返回json对象中文乱码问题
			if (converter instanceof MappingJackson2HttpMessageConverter) {
				((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
				((MappingJackson2HttpMessageConverter) converter).setObjectMapper(getObjectMapper());
			}
		}
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        super.configureMessageConverters(converters);
    }

	// 2.1:解决中文乱码后,返回json时可能会出现No converter found for return value of type: xxxx
	// 或这个:Could not find acceptable representation
	// 解决此问题如下
	public ObjectMapper getObjectMapper() {
		return new ObjectMapper();
	}

	// 2.2:解决No converter found for return value of type: xxxx
	public MappingJackson2HttpMessageConverter messageConverter() {
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		converter.setObjectMapper(getObjectMapper());
		return converter;
	}
}