如何解决Spring Boot中的中文乱码问题?

简介: Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。Spring Boot 被认为是 Spring MVC 的“接班人”,它可以帮我们自动配置,如果默认配置不能满足需求,我们还可以替换掉自动配置类,使用自己的配置。

前言

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。Spring Boot 被认为是 Spring MVC 的“接班人”,它可以帮我们自动配置,如果默认配置不能满足需求,我们还可以替换掉自动配置类,使用自己的配置。

一、如何解决Spring Boot中的中文乱码问题?

  1. 编写返回内容包含中文的API;

随便在一个Spring Boot项目中的controller中添加一个API,如下:

@GetMapping("/api/hello")
public JSONObject sayHello() {
JSONObject test = new JSONObject();
test.put("name", "dylanz");
test.put("say", "您好");
return test;
}

  1. 中文乱码演示;

    我们会发现,API返回中,英文正常显示,而中文却乱码了!原因先不分析,我们先来看看怎么解决!

  2. 解决中文乱码:(方法一);

如何解决呢,非常简单,修改一下API:

@GetMapping("/api/hello")
public JSONObject sayHello() {
HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
assert response != null;
response.setCharacterEncoding("UTF-8");

JSONObject test = new JSONObject();
test.put("name", "dylanz");
test.put("say", "您好");
return test;

}

原理非常简单,就是在返回中的头部信息中指定字符集为UTF-8,亲测有效!

修复中文乱码
指定字符集为UTF-8

  1. 解决中文乱码:(方法二);

这种办法更为简单,比第一种还简单,只需要在API上指定produces即可,如:

@GetMapping(value = "/api/hello", produces = "application/json;charset=UTF-8")
public JSONObject sayHello() {
JSONObject test = new JSONObject();
test.put("name", "dylanz");
test.put("say", "您好");
return test;
}

这种方式同样可以解决中文乱码问题,亲测有效!

  1. 解决中文乱码:(方法三)- 全局解决中文乱码问题;

上述解决中文乱码的2种方式固然简单,但需要一个一个API添加,这不符合咱们的气质啊,正确的姿势应该是:全局解决中文乱码问题!
在config包内新建CharsetConfig.java类(类名不限,不是非得CharsetConfig),在该配置类中写入代码:

package com.github.dylanz666.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**

  • @author : dylanz
  • @since : 11/15/2020
    */
    @Configuration
    public class CharsetConfig extends WebMvcConfigurationSupport {
    @Bean
    public HttpMessageConverter responseBodyConverter() {

     return new StringHttpMessageConverter(
             StandardCharsets.UTF_8);
    

    }

    @Override
    public void configureMessageConverters(

         List<HttpMessageConverter<?>> converters) {
     super.configureMessageConverters(converters);
     converters.add(responseBodyConverter());
    
     FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
     FastJsonConfig fastJsonConfig = new FastJsonConfig();
     fastJsonConfig.setSerializerFeatures(
             SerializerFeature.PrettyFormat
     );
     List<MediaType> fastMediaTypes = new ArrayList<>();
     fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
     fastConverter.setSupportedMediaTypes(fastMediaTypes);
     fastConverter.setFastJsonConfig(fastJsonConfig);
    
     converters.add(fastConverter);
    

    }

    @Override
    public void configureContentNegotiation(

         ContentNegotiationConfigurer configurer) {
     configurer.favorPathExtension(false);
    

    }
    }

由于我使用的是fastjson,因此在configureMessageConverters中添加了fastjson对中文支持的配置代码。

编写完成后,删除(方法一)和(方法二)的支持代码后,重启项目,中文支持已经变成全局生效啦,亲测有效!
二、 中文正常显示演示;

  1. 中文乱码原因分析;
    1). 借用第三步解决乱码问题的代码,稍微做一下修改,打印出修改前的字符集:

@GetMapping("/api/hello")
public JSONObject sayHello() {
HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
assert response != null;
System.out.println("Default charset: " + response.getCharacterEncoding());

JSONObject test = new JSONObject();
test.put("name", "dylanz");
test.put("say", "您好");
return test;

}

2). 再次启动项目并访问API后:

中文乱码原因:

原因找到了,原来Spring Boot中的JSON默认字符集是:ISO-8859-1(如果返回是纯String,则字符集为UTF-8,且中文不会乱码)。
2.从浏览器或postman上也能看出默认的字符集设置:
默认字符集
3). 我们解决乱码后的字符集:

总结

至此,我们从2个维度、3种方法,解决了Spring Boot项目中中文乱码的问题:

API单独设置字符集;
全局设置字符集;
相关文章
|
4月前
|
IDE Java Maven
Spring Boot之如何解决Maven依赖冲突Maven Helper 安装使用
Spring Boot之如何解决Maven依赖冲突Maven Helper 安装使用
85 2
|
4月前
|
缓存 负载均衡 Java
Spring Cloud Alibaba client升级问题之升级报错如何解决
Spring Cloud Alibaba提供了一套在Spring Cloud框架基础上构建的微服务解决方案,旨在简化分布式系统的开发和管理;本合集将探讨Spring Cloud Alibaba在实际应用中的部署和使用技巧,以及该框架常见问题的诊断方法和解决步骤。
|
4月前
|
消息中间件 Java 测试技术
Spring Cloud Alibaba环境问题之测试环境失败如何解决
Spring Cloud Alibaba提供了一套在Spring Cloud框架基础上构建的微服务解决方案,旨在简化分布式系统的开发和管理;本合集将探讨Spring Cloud Alibaba在实际应用中的部署和使用技巧,以及该框架常见问题的诊断方法和解决步骤。
|
4月前
|
运维 监控 Java
Spring Cloud Alibaba分布式事务问题之事务commit失败如何解决
Spring Cloud Alibaba提供了一套在Spring Cloud框架基础上构建的微服务解决方案,旨在简化分布式系统的开发和管理;本合集将探讨Spring Cloud Alibaba在实际应用中的部署和使用技巧,以及该框架常见问题的诊断方法和解决步骤。
|
4月前
|
缓存 Java Spring
Spring 如何解决循环依赖?
Spring 如何解决循环依赖?
50 0
|
18天前
|
Java Windows Spring
Spring Boot CMD 运行日志输出中文乱码
Spring Boot CMD 运行日志输出中文乱码
11 0
|
4月前
|
缓存 Java 开发工具
【spring】如何解决循环依赖
【spring】如何解决循环依赖
184 56
|
4月前
|
Java API 对象存储
对象存储OSS产品常见问题之使用Spring Cloud Alibaba情况下文档添加水印如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
|
4月前
|
存储 Java Maven
Spring Cloud Alibaba服务问题之服务报错如何解决
Spring Cloud Alibaba提供了一套在Spring Cloud框架基础上构建的微服务解决方案,旨在简化分布式系统的开发和管理;本合集将探讨Spring Cloud Alibaba在实际应用中的部署和使用技巧,以及该框架常见问题的诊断方法和解决步骤。
|
缓存 Java 开发者
Spring 是如何解决 Bean 的循环依赖问题的?
Spring 是如何解决 Bean 的循环依赖问题的?
90 0
下一篇
云函数