`response.setCharacterEncoding("UTF-8")` **Servlet 2.4+ 支持**,Servlet 2.3 **不支持** (無此方法)。
| Servlet 版本 | 對應 Web 容器 | setCharacterEncoding 支持 |
|---|---|---|
| 2.3 | Tomcat 4.x / 5.0 | ❌ 無此方法 |
| 2.4 | Tomcat 5.5 / 6.0 | ✅ 支持 |
| 2.5 | Tomcat 6.0 / 7.0 | ✅ 支持 |
| 3.0+ | Tomcat 7.0+ / Jetty 9+ | ✅ 支持 |
// 設置響應內容類型 + 編碼 (一步到位)
response.setContentType("text/html;charset=UTF-8");
// 等價於:
// response.setCharacterEncoding("UTF-8");
// response.setContentType("text/html");
┌─────────────────────────────────────────────────────────────┐ │ 請求/響應編碼流向 │ ├─────────────────────────────────────────────────────────────┤ │ 客戶端請求 │ │ │ │ │ ▼ (URL/表單提交) │ │ ┌─────────────────────┐ request.setCharacterEncoding │ │ │ 1. 請求解碼 │ ◄────────────────────────────────── │ (POST 必須在讀參數前調用) │ │ ISO-8859-1 默認 │ │ │ └──────────┬──────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────┐ pageEncoding (JSP 編譯時) │ │ │ 2. JSP/服務端處理 │ ◄────────────────────────────────── │ <%@ page pageEncoding="UTF-8" %> │ │ 內部用 UTF-16 │ │ │ └──────────┬──────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────┐ response.setContentType / │ │ │ 3. 響應編碼 │ ◄────────────────────────────────── │ setCharacterEncoding (優先級高) │ │ contentType │ pageEncoding (優先級低) │ │ └──────────┬──────────┘ │ │ │ │ │ ▼ │ │ 瀏覽器接收 → 根據 Content-Type charset 解碼顯示 │ └─────────────────────────────────────────────────────────────┘
| 設置方式 | 優先級 | 作用階段 | 備註 |
|---|---|---|---|
| `response.setCharacterEncoding("UTF-8")` | 最高 (響應端) | 響應流寫入前 | Servlet 2.4+,覆蓋 contentType 中 charset |
| `response.setContentType("text/html;charset=UTF-8")` | 高 | 響應頭發送時 | **通用推薦**,同時設置類型和編碼 |
| `<%@ page pageEncoding="UTF-8" %>` | 中 (JSP 編譯) | JSP 編譯為 Servlet 時 | 影響 JSP 文件讀取、響應默認編碼 |
| `<%@ page contentType="text/html;charset=UTF-8" %>` | 中 | JSP 編譯時生成 response.setContentType | 等同於在生成的 Servlet 中調用 |
| `request.setCharacterEncoding("UTF-8")` | 最高 (請求端) | 讀取參數前 (`getParameter`) | **僅對 POST 有效**,GET 需配置 Tomcat `URIEncoding` |
useBodyEncodingForURI="true" />
**「請求解碼靠 `request.setCharacterEncoding` (POST)、`URIEncoding` (GET);響應編碼靠 `response.setContentType("text/html;charset=UTF-8")` (通用首選)」。** 統一全鏈路 UTF-8,配置 Tomcat `URIEncoding`,是解決中文亂碼的銀彈。