spring boot @responseBody 中文乱码解决方法

使用SpringBoot开发,对外开发接口供调用,传入参数中有中文,出现中文乱码,查了好多资料,总结解决方法如下:

第一步,约定传参编码格式

不管是使用httpclient,还是okhttp,都要设置传参的编码,为了统一,这里全部设置为utf-8

第二步,修改application.properties文件

增加如下配置(以yml配置为主):

server:
  tomcat:
    uri-encoding: utf-8
 
spring:
  http:
    encoding:
      force: true
      charset: utf-8
      enabled: true

此时拦截器中返回的中文已经不乱码了,但是controller中返回的数据依旧乱码。

第三步,修改controller的@RequestMapping

修改如下:

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

这种方法的弊端是限定了数据类型,继续查找资料,在stackoverflow上发现解决办法,是在配置类中增加如下代码:

/**
 * 注解配置类
 * @author lich
 *
 */
@SpringBootConfiguration
public class WebConfig extends WebMvcConfigurerAdapter {

    /**
	 * 设置响应的字符编码
	 * @return
	 */
    @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

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值