解决SpringBoot 中文乱码问题【Tomcat、中创】
首先,当出现乱码问题了一定是各方面规定的编码格式不一致导致的
1、第一步检查页面编码格式,一般来说都是国际统一编码【UTF-8】,这里就以JSP为例:
要注意上面圈出来的表示页面编码格式的参数
2、第二步检查项目中编码格式,SpringBoot的项目统一编码格式可以在 application.properties
或 application.yml
文件中设置
## http编码
spring.http.encoding.charset=UTF-8
## 消息编码
spring.messages.encoding=UTF-8
## 文件编码
spring.banner.charset=UTF-8
3、第三步检查部署应用服务器的编码格式,当然一般都可以在项目配置文件中配置,也可以在应用服务器配置文件中配置
项目配置文件(application.properties)中配置:
## tomcat编码
server.tomcat.uri-encoding=UTF-8
应用服务器配置文件(server.xml)中配置:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" />
一般通过以上三种问题排查之后都会解决乱码问题,如果实在还没的话可以debug查看是否前台传过来之后就乱码,可以通过配置类的方式来解决或者代码中强制转换类型
配置类
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.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.List;
/**
* 中文乱码解决
*/
@Configuration
public class CharsetConfig implements WebMvcConfigurer {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(responseBodyConverter());
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
顺便分享一下本人之前在项目中遇到的一个乱码问题,使用的是国产应用服务器中创
本人在本地开发中一直都是用的tomcat应用服务器,但是项目开发完之后准备到测试服务器用中创测试的时候发现了乱码问题,本人问题排查第一、二步没问题,关于第三步我单独在中创应用配置文件中并无发现配置编码格式的参数,后面还是在中创人员的帮助下解决的:
在项目中WEB-INF下添加 inforsuite-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<inforsuite-web-app>
<property name="allowLinking" value="true"></property>
<!-- <class-loader delegate="false"/>-->
<locale-charset-info>
<parameter-encoding default-charset="UTF-8" />
</locale-charset-info>
<!-- 下面是数据库连接池配置,可以忽略 -->
<datasources>
<resource-ref>
<res-ref-name>highgo</res-ref-name>
<jndi-name>jdbc/jdbc_highgo</jndi-name>
</resource-ref>
</datasources>
</inforsuite-web-app>