首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JSP Servlet 少數民族語言(藏文)參數傳遞亂碼:Base64 編碼傳輸方案

     編輯:程式設計綜合問答

問題場景

JSP 表單包含藏文輸入框,提交到 Servlet 時參數變為亂碼,Base64 轉碼也無法恢復。

根本原因

  1. 瀏覽器提交表單默認使用頁面編碼(如 UTF-8)對參數進行 URL 編碼。
  2. Tomcat 默認用 ISO-8859-1 解碼 URL 參數,導致多字節字符(藏文)解析錯誤。
  3. Servlet 中 request.getParameter() 獲取的已是錯誤字節序列,後續 Base64 無法修復。

解決方案:前端預編碼 + 後端解碼

核心思路:在 JSP 中使用 JavaScript 將藏文轉為 Base64 字符串提交,Servlet 再解碼,繞過容器 URL 解碼環節。

前端 JSP

<form id="tibetanForm" action="SaveServlet" method="post">
    <textarea name="tibetanContent" id="tibetanContent"></textarea>
    <input type="hidden" name="encodedContent" id="encodedContent" />
    <button type="button" onclick="submitForm()">提交</button>
</form>

<script>
function submitForm() {
    var raw = document.getElementById('tibetanContent').value;
    // UTF-8 轉 Base64
    var encoded = btoa(unescape(encodeURIComponent(raw)));
    document.getElementById('encodedContent').value = encoded;
    document.getElementById('tibetanForm').submit();
}
</script>

後端 Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String encoded = request.getParameter("encodedContent");
    if (encoded != null) {
        try {
            // Base64 解碼還原 UTF-8 字符串
            byte[] decodedBytes = Base64.getDecoder().decode(encoded);
            String tibetan = new String(decodedBytes, StandardCharsets.UTF_8);
            // 存入數據庫(確保數據庫連接 useUnicode=true&characterEncoding=UTF-8)
            saveToDatabase(tibetan);
        } catch (IllegalArgumentException e) {
            // 處理非法 Base64
        }
    }
}

替代方案:統一容器編碼

若不想改動前端,需確保全鏈路 UTF-8:

  1. JSP 頁面指令:<%@ page contentType="text/html;charset=UTF-8" %>
  2. Tomcat server.xml:<Connector URIEncoding="UTF-8" />
  3. Servlet 過濾器:request.setCharacterEncoding("UTF-8")
  4. 數據庫連接串:?useUnicode=true&characterEncoding=UTF-8

但某些老舊環境或代理服務器可能仍導致編碼不一致,Base64 方案更穩健、可控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved