温馨提示×

怎样解决debian tomcat乱码

小樊
38
2026-10-06 10:21:39
栏目: 智能运维

在 Debian 上运行 Tomcat 出现乱码(中文乱码、日志乱码、页面乱码等),通常是因为字符编码不一致导致的。下面按常见场景 + 解决方案给你一个完整排查指南。


一、先确认系统字符集(最重要)

1. 查看系统编码

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

二、Tomcat 启动环境乱码(日志乱码)

2. 设置 Tomcat 启动编码

编辑:

/etc/default/tomcat9   # 或 tomcat8 / tomcat10

添加或修改:

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

或:

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

重启 Tomcat:

systemctl restart tomcat9

三、Tomcat 自身配置乱码

3. 修改 server.xml(请求/响应乱码)

编辑:

/etc/tomcat9/server.xml

Connector 增加:

<Connector
    port="8080"
    protocol="HTTP/1.1"
    URIEncoding="UTF-8"
    useBodyEncodingForURI="true"
/>

四、Web 应用层乱码(JSP / Servlet)

4. JSP 页面乱码

JSP 顶部加:

<%@ page contentType="text/html;charset=UTF-8" %>

5. Servlet 中设置编码

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

6. Spring 项目

在 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>

五、日志文件乱码(catalina.out)

7. 修改 logging.properties

编辑:

/etc/tomcat9/logging.properties

确保:

java.util.logging.ConsoleHandler.encoding = UTF-8

六、数据库乱码(常见问题)

8. MySQL 乱码

JDBC URL:

jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8

MySQL 配置:

[mysqld]
character-set-server=utf8mb4

七、快速自查清单 ✅

  • [ ] Debian 系统 locale 是 UTF-8
  • [ ] Tomcat 启动参数含 -Dfile.encoding=UTF-8
  • [ ] server.xml 有 URIEncoding="UTF-8"
  • [ ] JSP / Servlet 设置 UTF-8
  • [ ] 数据库字符集是 UTF-8

八、如果你愿意

你可以告诉我:

  • Tomcat 版本(8 / 9 / 10)
  • 乱码场景(页面 / 日志 / 表单 / 数据库)
  • 示例乱码内容

我可以给你精确修改方案。

0 踩