美文网首页
解决SpringBoot中文乱码问题-亲测有效

解决SpringBoot中文乱码问题-亲测有效

作者: 茶还是咖啡 | 来源:发表于2021-08-05 09:24 被阅读0次
    1. 检查application.yml
      一般情况都是默认配置的UTF-8不需要自己配置,检查一下就好~
    server:
      tomcat:
        uri-encoding: UTF-8
    spring:
      http:
        encoding:
          charset: UTF-8
      messages:
        encoding: UTF-8
    
    1. 添加配置类
    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.WebMvcConfigurer;
    
    import java.nio.charset.Charset;
    import java.util.List;
    
    /**
     * 中文乱码解决
     */
    @Configuration
    public class CharsetConfig implements WebMvcConfigurer {
    
        @Bean
        public HttpMessageConverter<String> responseBodyConverter() {
            StringHttpMessageConverter converter = new StringHttpMessageConverter(
                    Charset.forName("UTF-8"));
            return converter;
        }
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(responseBodyConverter());
        }
    
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.favorPathExtension(false);
        }
    }
    

    相关文章

      网友评论

          本文标题:解决SpringBoot中文乱码问题-亲测有效

          本文链接:https://www.haomeiwen.com/subject/qlqmvltx.html