解决SpringBoot 中文乱码问题【Tomcat、中创】

解决SpringBoot 中文乱码问题【Tomcat、中创】

首先,当出现乱码问题了一定是各方面规定的编码格式不一致导致的

1、第一步检查页面编码格式,一般来说都是国际统一编码【UTF-8】,这里就以JSP为例:
在这里插入图片描述

要注意上面圈出来的表示页面编码格式的参数

2、第二步检查项目中编码格式,SpringBoot的项目统一编码格式可以在 application.propertiesapplication.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>
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值