springboot解決返回前臺json資料中文變?問題
阿新 • • 發佈:2018-12-09
import com.fasterxml.jackson.databind.ObjectMapper; 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.http.converter.json.MappingJackson2HttpMessageConverter; //import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.List; @Configuration public class InterceptorConfig extends WebMvcConfigurationSupport { // public void addInterceptors(InterceptorRegistry registry) { //// addPathPatterns新增需要攔截的名稱空間; //// excludePathPatterns新增排除攔截名稱空間 // registry.addInterceptor(new PassportInterceptor()).addPathPatterns("/**").excludePathPatterns("/register"); // } @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()); //解決 新增解決中文亂碼後 上述配置之後,返回json資料直接報錯 500:no convertter for return value of type converters.add(messageConverter()); } @Bean public MappingJackson2HttpMessageConverter messageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(getObjectMapper()); return converter; } @Bean public ObjectMapper getObjectMapper() { return new ObjectMapper(); } }