萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Tomcat 中文亂碼徹底解決:URIEncoding 配置與 Servlet 響應編碼雙重保障

Tomcat 默認 URIEncoding=ISO-8859-1,導致 GET 參數中文亂碼;響應默認編碼不一致導致輸出亂碼。雙管齊下徹底解決。

方案一:配置 Connector URIEncoding (解決 GET 請求參數亂碼)

修改 $CATALINA_HOME/conf/server.xml,找到 <Connector port="8080" ...> 添加屬性:

<Connector port="8080" 
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true"
           URIEncoding="UTF-8" />

建議統一用 UTF-8 (而非 GBK),全鏈路一致:數據庫、連接池、JVM、前端頁面 <meta charset="UTF-8">、JS 文件編碼、HTTP Header Content-Type: text/html; charset=UTF-8。

方案二:Servlet 代碼設置響應編碼 (解決輸出亂碼)

public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        // 必須在獲取 Writer/OutputStream 前設置
        resp.setContentType("text/html; charset=UTF-8"); 
        // 等價於 resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html");
        
        PrintWriter out = resp.getWriter();
        out.write("中文測試正常");
    }
}

進階:全局過濾器統一設置 (推薦)

@WebFilter("/*")
public class EncodingFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 
            throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");    // POST 請求體解碼
        resp.setCharacterEncoding("UTF-8");   // 響應編碼
        resp.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, resp);
    }
}

Spring Boot 直接配置:

server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true

POST 請求亂碼補充

POST 表單提交亂碼需在讀取參數前調用 request.setCharacterEncoding("UTF-8"),或配置上述過濾器。URIEncoding **不影響 POST**。

驗證清單

  1. 重啟 Tomcat 生效 server.xml 修改。
  2. 瀏覽器 Network 面板確認 Request URL 參數編碼正確 (%E4%B8%AD%E6%96%87)。
  3. Response Headers 含 Content-Type: text/html; charset=UTF-8。
  4. 數據庫表/列字符集為 utf8mb4,連接串 characterEncoding=UTF-8。

統一 UTF-8 全鏈路,中文亂碼徹底告別。

copyright © 萬盛學電腦網 all rights reserved