Spring Boot 中文亂碼解決

來源:互聯網
上載者:User

使用SpringBoot開發,對外開發介面供調用,傳入參數中有中文,出現中文亂碼,查了好多資料,總結解決方案如下: 第一步,約定傳參編碼格式

不管是使用httpclient,還是okhttp,都要設定傳參的編碼,為了統一,這裡全部設定為utf-8 第二步,修改application.properties檔案

增加如下配置:

spring.http.encoding.force=truespring.http.encoding.charset=UTF-8spring.http.encoding.enabled=trueserver.tomcat.uri-encoding=UTF-8

此時攔截器中返回的中文已經不亂碼了,但是controller中返回的資料依舊亂碼。 第三步,修改controller的@RequestMapping

修改如下:

produces="text/plain;charset=UTF-8"

這種方法的弊端是限定了資料類型,繼續尋找資料,在stackoverflow上發現解決辦法,是在配置類中增加如下代碼:

@Configurationpublic class CustomMVCConfiguration extends WebMvcConfigurerAdapter {    @Bean    public HttpMessageConverter<String> responseBodyConverter() {        StringHttpMessageConverter converter = new StringHttpMessageConverter(                Charset.forName("UTF-8"));        return converter;    }    @Override    public void configureMessageConverters(            List<HttpMessageConverter<?>> converters) {        super.configureMessageConverters(converters);        converters.add(responseBodyConverter());    }    @Override    public void configureContentNegotiation(            ContentNegotiationConfigurer configurer) {        configurer.favorPathExtension(false);    }}

便可以解決SpringBoot的中文亂碼問題了。
ps:stackoverflow網址
http://stackoverflow.com/questions/27606769/how-to-overwrite-stringhttpmessageconverter-default-charset-to-use-utf8-in-sprin
http://stackoverflow.com/questions/20935969/make-responsebody-annotated-spring-boot-mvc-controller-methods-return-utf-8

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.