Springboot 解決返回中文亂碼問題
阿新 • • 發佈:2019-01-08
package com.caib.commons.handlerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.stereotype.Component; 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; /** * @Author 盪漾 * @email
[email protected] * @description: 配置攔截器 * @create 2018-11-20 16:14 */ @Component public class MvcConfigurer extends WebMvcConfigurationSupport { //解決中文亂碼問題 @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 addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SecurityHandlerInterceptor()) //新增過濾url ** 代表所有 .addPathPatterns("/**") //新增排除過濾url .excludePathPatterns( "/swagger-resources/**" , "/webjars/**" , "/v2/**" , "/swagger-ui.html/**" ,"/register" ,"/login" ,"/**/error"); ; super.addInterceptors(registry); } /** * 解決resources下面靜態資源無法訪問 * @param registry */ /* @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("classpath:/gen","classpath:application.yml","classpath:logback.xml"); super.addResourceHandlers(registry); }*/ /* @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**")//設定允許跨域的路徑 .allowedOrigins("*")//設定允許跨域請求的域名 .allowCredentials(true)//是否允許證書 不再預設開啟 .allowedMethods("POST")//設定允許的方法"GET", "POST", "PUT", "DELETE" .maxAge(3600);//跨域允許時間 }*/ }
直接在你的攔截器裡新增如下程式碼即可
//解決中文亂碼問題
@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());
}