在使用 Spring 整合 Hibernate 進行中文數據持久化時,亂碼問題是開發者常遇到的棘手難題。本文總結了兩種行之有效的解決方案,並分析其核心原理。
mysql --default-character-set=gb2312 -u root -pCREATE TABLE ... DEFAULT CHARACTER SET gb2312;<property name="url">
<value>jdbc:mysql://localhost/struts?useUnicode=true&characterEncoding=gb2312</value>
</property>
關鍵點:連接串必須顯式指定 useUnicode=true 並設置 characterEncoding=gb2312,否則驅動程序無法正確處理中文編碼轉換。
<property name="url">
<value>jdbc:mysql://localhost/struts</value>
</property>
此時不指定字符集,由應用層負責編碼轉換。
無論採用哪種方案,在 JSP 接收請求參數時,通常都需要進行 ISO-8859-1 → GB2312 轉換(因為 Tomcat 默認按 ISO-8859-1 解碼 URL 參數):
public class EncodingUtil {
public static String trans(String chi) {
if (chi == null) return null;
try {
// 先按 ISO-8859-1 還原字節,再按 GB2312 解碼
byte[] temp = chi.getBytes("ISO-8859-1");
return new String(temp, "GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return chi;
}
}
public static String trans(Object obj) {
return obj == null ? null : trans(obj.toString());
}
}
使用示例:
String name = EncodingUtil.trans(request.getParameter("name"));
亂碼本質是編碼與解碼不一致導致的字節序列錯誤解讀。流程如下:
ISO-8859-1 解碼字節為 Java 字符串(此時已產生錯誤字符)。ISO-8859-1 還原原始字節,再按真實編碼(GB2312/UTF-8)重新解碼。方案一在數據庫、連接池、應用層統一編碼,鏈路最短;方案二在應用層手動修正,靈活但易遺漏。
server.xml 的 Connector 添加 URIEncoding="UTF-8" 解決 GET 參數亂碼。CharacterEncodingFilter 統一強制請求/響應編碼。