Springboot 编码格式设置为UTF-8

Springboot 编码格式设置为UTF-8


1.配置文件新增属性

// 文件格式为yml

spring:
#--------------------------charset--------------------------
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true

#--------------------------Server--------------------------
server:
  tomcat:
    uri-encoding: UTF-8

2.向Spring注册一个自定义的StringHttpMessageConverter用于string转码

// 基于Springboot2.0.1.RELEASE

import com.simply.zuozuo.interceptor.HandleInterceptorImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
        // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案
        // 百度,谷歌,各大论坛等。你可以试试去掉。
        addDefaultHttpMessageConverters(converters);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_15071263/article/details/80248805