在 Debian 上运行 Tomcat 出现乱码,通常不是“Tomcat 本身坏了”,而是字符编码配置不一致导致的。下面按最常见原因 → 解决方式说明。
Tomcat(尤其老版本)默认编码不是 UTF-8,而是:
ISO-8859-1
如果你的页面、数据库、请求参数是 UTF-8,就会乱码。
server.xml(最重要)编辑:
/etc/tomcat9/server.xml
(版本不同可能是 tomcat8 / tomcat10)
找到:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
改成:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"
useBodyEncodingForURI="true" />
✅ 作用:
URIEncoding="UTF-8":解决 GET 参数乱码useBodyEncodingForURI:POST 也按 UTF-8Debian 默认 locale 可能不是 UTF-8。
编辑 Tomcat 启动环境:
/etc/default/tomcat9
添加或修改:
JAVA_OPTS="-Dfile.encoding=UTF-8"
然后重启:
systemctl restart tomcat9
在 web.xml 加:
<filter>
<filter-name>encoding</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>
</filter>
或 Java 代码:
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
locale
如果不是:
LANG=en_US.UTF-8
或
LANG=zh_CN.UTF-8
apt install locales
dpkg-reconfigure locales
勾选:
zh_CN.UTF-8
en_US.UTF-8
Tomcat 日志乱码,改:
/etc/tomcat9/logging.properties
确保:
java.util.logging.ConsoleHandler.encoding = UTF-8
| 项目 | 是否 UTF-8 |
|---|---|
| server.xml | ✅ |
| JAVA_OPTS | ✅ |
| 页面 charset | ✅ |
| 数据库 | ✅ |
| Linux locale | ✅ |
你可以告诉我:
tomcat9? 10?)我可以直接给你最小化修改方案。