SpringBoot解决中文乱码问题(亲测有效)
2019-01-24 本文已影响29人
1ff5a98e5398
传统方式
在application.properties中添加
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
但是,经过测试加上这个依然解决不了乱码问题。
解决方式一
直接在每个Mapping上添加 produces = "application/json;charset=utf-8"
@GetMapping(value = "/api/v1/getRecords", produces = "application/json;charset=utf-8")
虽然这样也能解决中文乱码问题,但是却不是那么优雅而且工作量多且重复
解决方式二
package xyz.loger.accountsappserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
/**
*
*/
@Slf4j
@Order(1)
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
stringHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
return stringHttpMessageConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(responseBodyConverter());
}
}