首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Eclipse 開發 Struts 亂碼三大場景完美解決方案

     編輯:Java 程式設計入門

Eclipse 開發 Struts 專案常遇三類中文亂碼,對症下藥即可根治。

1. 資源檔中文 Value 顯示亂碼

原因:Properties 檔案儲存為 ISO-8859-1,中文需 Unicode 轉義。
解法:安裝 Eclipse 外掛 Properties Editor,自動處理編碼轉換與反轉義,所見即所得編輯中文。

2. 表單文字域輸入中文亂碼

原因:請求參數解碼預設 ISO-8859-1,與頁面編碼(UTF-8/GBK)不符。
解法:配置 Servlet Filter 統一設定請求編碼。最簡單:直接引用 Tomcat 內建 SetCharacterEncodingFilter:

<filter>
  <filter-name>SetCharacterEncoding</filter-name>
  <filter-class>filters.SetCharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>GBK</param-value>  <!-- 或 UTF-8 -->
  </init-param>
</filter>
<filter-mapping>
  <filter-name>SetCharacterEncoding</filter-name>
  <url-pattern>*.do</url-pattern>
</filter-mapping>

3. 資料庫讀出中文亂碼

原因:JDBC 驅動以錯誤編碼(常為 ISO-8859-1)解碼資料庫位元組。
解法:在 Java 端手工轉碼修正(治標),或修正資料庫/驅動/連線 URL 編碼設定(治本)。手工修正範例:

while (rs.next()) {
    String col1 = rs.getString(1);
    String col2 = rs.getString(2);
    // 將錯誤解碼的字串按 ISO-8859-1 還原位元組,再按正確編碼重組
    col1 = new String(col1.getBytes("ISO-8859-1"), "GB2312");
    col2 = new String(col2.getBytes("ISO-8859-1"), "GB2312");
    // ...
}

建議:統一資料庫、連線池、驅動、頁面編碼為 UTF-8,從源頭杜絕亂碼。

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