Spring+Hibernate亂碼解決方案
今天用spring+hibernate進行中文插入時出現亂碼問題,通過查資料和自己反復測試終于解決了.
總結了兩種方法:
1、使用gb2312編碼,變更mysql的數據庫編碼字符集。cmd模式下用mysql --default-character-set=gb2312 -u root -p進入,然后再每個建表語句后增加default character set gb2312;
重新建立數據表。
值得注意的地方是:applicationContext.xml中的數據庫連接必須設置為<property name="url"><value>jdbc:mysql://localhost/struts?useUnicode=true&characterEncoding=gb2312</value></property>,這樣插入的才是正常的中文,否則就是亂碼。
2、在進行數據保存之前進行gb2312到iso8859-1編碼的轉換,applicationContext.xml中的數據庫連接必須設置為<property name="url"><value>jdbc:mysql://localhost/struts</value></property>,這樣插入的才是正常的中文,否則就是亂碼。
它們相同的地方是在用jsp進行中文內容填加時,都要進行gb2312到iso8859-1編碼的轉換:
總結了兩種方法:
1、使用gb2312編碼,變更mysql的數據庫編碼字符集。cmd模式下用mysql --default-character-set=gb2312 -u root -p進入,然后再每個建表語句后增加default character set gb2312;
重新建立數據表。
值得注意的地方是:applicationContext.xml中的數據庫連接必須設置為<property name="url"><value>jdbc:mysql://localhost/struts?useUnicode=true&characterEncoding=gb2312</value></property>,這樣插入的才是正常的中文,否則就是亂碼。
2、在進行數據保存之前進行gb2312到iso8859-1編碼的轉換,applicationContext.xml中的數據庫連接必須設置為<property name="url"><value>jdbc:mysql://localhost/struts</value></property>,這樣插入的才是正常的中文,否則就是亂碼。
它們相同的地方是在用jsp進行中文內容填加時,都要進行gb2312到iso8859-1編碼的轉換:
| String name; name=trans(request.getParameter("name")); String trans(String chi) { String result = null; byte temp []; try { temp=chi.getBytes("iso-8859-1"); result = new String(temp); } catch(java.io.UnsupportedEncodingException e) { System.out.println (e.toString()); } return result; } String trans(Object chi) { return trans(chi.toString()); } |