温馨提示×

debian Tomcat为何乱码

小樊
53
2026-09-06 14:16:56
栏目: 智能运维

在 Debian 上运行 Tomcat 出现乱码,通常不是“Tomcat 本身坏了”,而是字符编码配置不一致导致的。下面按最常见原因 → 解决方式说明。


一、最常见原因(90% 的情况)

1️⃣ Tomcat 默认使用 ISO-8859-1

Tomcat(尤其老版本)默认编码不是 UTF-8,而是:

ISO-8859-1

如果你的页面、数据库、请求参数是 UTF-8,就会乱码。


二、必须改的核心配置

✅ 1. 修改 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-8

✅ 2. 设置 JVM 默认编码(非常关键)

Debian 默认 locale 可能不是 UTF-8。

编辑 Tomcat 启动环境:

/etc/default/tomcat9

添加或修改:

JAVA_OPTS="-Dfile.encoding=UTF-8"

然后重启:

systemctl restart tomcat9

三、应用层面也要统一

✅ 3. Servlet / Filter 设置 UTF-8

在 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");

四、Linux 系统 locale 问题(常被忽略)

检查:

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 ✅

七、如果你愿意,我可以更精准帮你

你可以告诉我:

  1. Tomcat 版本(tomcat9? 10?)
  2. 乱码场景(页面 / 日志 / 数据库 / 接口)
  3. 中文还是其他语言
  4. Debian 版本

我可以直接给你最小化修改方案。

0 踩