SpringBoot⼏种中⽂乱码解决办法1.直接返回中⽂字符串乱码
⽐如下⾯这段代码:
@RequestMapping(value ="/upload")
public String upload(@RequestParam("file1") MultipartFile file){
springboot中文if(file.isEmpty()){
return"⽂件为空";
}
// 获取⽂件名
String fileName = OriginalFilename();
System.out.println("上传的⽂件名为:"+ fileName);
// 获取⽂件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:"+ suffixName);
// ⽂件上传后的路径
String filePath ="D:/backgroundimagefroidea/";
// 解决中⽂问题,liunx下中⽂路径,图⽚显⽰问题
// fileName = UUID.randomUUID() + suffixName;
File dest =new File(filePath + fileName);
// 检测是否存在⽬录
if(!ParentFile().exists()){
}
try{
return"上传成功";
}catch(IllegalStateException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return"上传失败";
}
springboot2.x版本解决办法:
实现WebMvcConfigurer并添加转换器
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/file/**").addResourceLocations("file:///D:/backgroundimagefroidea/");
}
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","POST","PUT","DELETE")
.allowCredentials(true)
.
maxAge(3600)
.allowedHeaders("Authorization","content-type","x-requested-with")
.exposedHeaders("X-Sample");
/*
注意exposeHeaders为暴露header,前端可以通过ajax的⽅式获取response中暴露的header
success: function(data, textStatus, request){
console.log(data);
console.ResponseHeader("X-Sample"));
console.ResponseHeader("content-type"));
},
*/
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
StringHttpMessageConverter converter =new StringHttpMessageConverter(
Charset.forName("UTF-8"));
converters.add(converter);
}
}
2.返回的对象含中⽂(乱码)
由于增加了上⾯的转换器,spring默认的json转换器MappingJackson2HttpMessageConverter就失效了,导致直接返回对象时中⽂乱码,⽐如下⾯这段代码:
@RequestMapping(value ="/getBook")
public Object getBook(HttpServletRequest request){
Enumeration<String> headerNames = HeaderNames();
while(headerNames.hasMoreElements()){
String key = Element();
System.out.println(key +":"+ Header(key));
}
Book b =new Book();
b.setId("1111");
b.setName("西游记");
b.setAuthor("罗贯中");
return b;
}
解决办法:
添加FastJsonHttpMessageConverter转换器
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/file/**").addResourceLocations("file:///D:/backgroundimagefroidea/");
}
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOrigins("*")
.
allowedMethods("GET","POST","PUT","DELETE")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("Authorization","content-type","x-requested-with")
.exposedHeaders("X-Sample");
/*
注意exposeHeaders为暴露header,前端可以通过ajax的⽅式获取response中暴露的header
success: function(data, textStatus, request){
console.log(data);
console.ResponseHeader("X-Sample"));
console.ResponseHeader("content-type"));
},
*/
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
StringHttpMessageConverter converter =new StringHttpMessageConverter(
Charset.forName("UTF-8"));
converters.add(converter);
//1.需要定义⼀个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter =new FastJsonHttpMessageConverter();
//2.添加fastJson的配置信息,⽐如:是否要格式化返回的json数据;
FastJsonConfig fastJsonConfig =new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteDateUseDateFormat);
//3处理中⽂乱码问题
List<MediaType> fastMediaTypes =new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//5.将convert添加到converters当中.
converters.add(fastJsonHttpMessageConverter);
}
}
3.spring-boot:run启动的项⽬中⽂乱码
当⽤spring-boot:run启动项⽬后,访问控制器时会发现每⼀处中⽂都时乱码。
解决⽅法:
增加jvm参数“-ding=UTF-8”
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8081 -ding=UTF-8"
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论