在 Debian 上运行 Tomcat 出现乱码(中文乱码、日志乱码、页面乱码等),通常是因为字符编码不一致导致的。下面按常见场景 + 解决方案给你一个完整排查指南。
locale
正常应类似:
LANG=zh_CN.UTF-8
LC_ALL=zh_CN.UTF-8
如果不是 UTF-8,先修复系统编码:
sudo apt install locales
sudo dpkg-reconfigure locales
勾选 zh_CN.UTF-8 或 en_US.UTF-8
然后:
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
编辑:
/etc/default/tomcat9 # 或 tomcat8 / tomcat10
添加或修改:
JAVA_OPTS="-Dfile.encoding=UTF-8"
或:
CATALINA_OPTS="-Dfile.encoding=UTF-8"
重启 Tomcat:
systemctl restart tomcat9
编辑:
/etc/tomcat9/server.xml
Connector 增加:
<Connector
port="8080"
protocol="HTTP/1.1"
URIEncoding="UTF-8"
useBodyEncodingForURI="true"
/>
JSP 顶部加:
<%@ page contentType="text/html;charset=UTF-8" %>
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
在 web.xml 加:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
编辑:
/etc/tomcat9/logging.properties
确保:
java.util.logging.ConsoleHandler.encoding = UTF-8
JDBC URL:
jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
MySQL 配置:
[mysqld]
character-set-server=utf8mb4
-Dfile.encoding=UTF-8URIEncoding="UTF-8"你可以告诉我:
我可以给你精确修改方案。