上次測(cè)試使用hibernate,遇到了中文的亂碼問題,今天在web中使用hibernate又遇到了亂碼的問題。但是上次解決后沒有把解決方案記錄下來,今天重新上網(wǎng)搜索了一把。并將解決方案記錄在下面便于以后再遇到時(shí)查看用。
Hibernate中配置Mysql數(shù)據(jù)庫如下:
hibernate.dialect net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class org.gjt.mm.mysql.Driver
#hibernate.connection.driver_class com.mysql.jdbc.Driver
hibernate.connection.url jdbc:mysql://localhost:3306/test
hibernate.connection.username root
hibernate.connection.password password
在hibernate.commection.url的值后面加上字符串“?useUnicode=true&characterEncoding=GBK”就可以解決了。
即修改后的url為:
hibernate.connection.url jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK
Hibernate還有一種配置文件是xml格式的,文件名為:hibernate.cfg.xml
在xml文件中配置MySql數(shù)據(jù)庫的定義如下:
<session-factory name="/jndi/ContactsSessionFactory">
<!-- properties -->
<property name="hibernate.connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">
net.sf.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.pool_size">4</property>
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="hello/Message.hbm.xml"/>
</session-factory>
注意由于在XML文件中&符號(hào)是轉(zhuǎn)義符,因此需要對(duì)其進(jìn)行轉(zhuǎn)義。即使用&來代替。
JSP連接MYSQL數(shù)據(jù)庫如果有中文存取的情況會(huì)出現(xiàn)亂碼,網(wǎng)頁上中文顯示一堆“?“,
需要做如下改變
1. 連接串:
String mysqlDriver = "org.gjt.mm.mysql.Driver"; //數(shù)據(jù)庫驅(qū)動(dòng),又作"com.mysql.jdbc.Driver"
String mysqlUrl = "jdbc:mysql://localhost:3306/bbs?useUnicode=true&characterEncoding=gb2312"; //數(shù)據(jù)庫連接字串
String mysqlUser = "root"; //數(shù)據(jù)庫用戶名
String mysqlPsw = ""; //數(shù)據(jù)庫密碼
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); //注冊(cè)驅(qū)動(dòng)
conn = DriverManager.getConnection(mysqlUrl,mysqlUser,mysqlPsw); //得到連接
2.請(qǐng)求對(duì)象設(shè)置:
<% request.setCharacterEncoding("gb2312");%>
將jsp的請(qǐng)求對(duì)象的字符集設(shè)置為支持中文
這中方法還沒用過,先收藏起來,有空的時(shí)候研究一下。