1.直接返回中文字符串乱码
比如下面这段代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31@RequestMapping(value = "/upload") public String upload(@RequestParam("file1") MultipartFile file) { if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename(); 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 (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上传成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上传失败"; }
springboot2.x版本解决办法:
实现WebMvcConfigurer并添加转换器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34@Configuration @EnableWebMvc public class CustomMvcConfiguration1 implements WebMvcConfigurer { @Override 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.log(request.getResponseHeader("X-Sample")); console.log(request.getResponseHeader("content-type")); }, */ } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { StringHttpMessageConverter converter = new StringHttpMessageConverter( Charset.forName("UTF-8")); converters.add(converter); } }
2.返回的对象含中文(乱码)
由于增加了上面的转换器,spring默认的json转换器MappingJackson2HttpMessageConverter就失效了,导致
直接返回对象时中文乱码,比如下面这段代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14@RequestMapping(value = "/getBook") public Object getBook(HttpServletRequest request) { Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = headerNames.nextElement(); System.out.println(key + ":" + request.getHeader(key)); } Book b = new Book(); b.setId("1111"); b.setName("西游记"); b.setAuthor("罗贯中"); return b; }
解决办法:
添加FastJsonHttpMessageConverter转换器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52@Configuration @EnableWebMvc public class CustomMvcConfiguration1 implements WebMvcConfigurer { @Override 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.log(request.getResponseHeader("X-Sample")); console.log(request.getResponseHeader("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参数“-Dfile.encoding=UTF-8”
复制代码
1
2mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8081 -Dfile.encoding=UTF-8"
最后
以上就是如意灰狼最近收集整理的关于SpringBoot几种中文乱码解决办法的全部内容,更多相关SpringBoot几种中文乱码解决办法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复