弄了老半天,終于是把這個問題給搞定了,一個在JOBSS下跑得很好的程序,因為某些原因需要遷移到TOMCAT下面,可老是出現(xiàn)亂碼的問題,情況如下
數(shù)據(jù)庫:MYSQL5.0
數(shù)據(jù)庫編碼:UTF-8
所有頁面編碼都統(tǒng)一用UTF-8
在JBOSS下配置數(shù)據(jù)源,即修改mysql-ds.xml
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>app</jndi-name>
<connection-url>jdbc:mysql://localhost/app</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>user</user-name>
<password>pwd</password>
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
當把應用遷移到TOMCAT6下時,配置好TOMCAT下的數(shù)據(jù)源(修改contex.xml文件)
<?xml version='1.0' encoding='utf-8'?>
<!-- The contents of this file will be loaded for each web application -->
<Context>
<Resource name="jdbc/app"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/app"
username="user"
password="pwd"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
maxActive="700"
maxIdle="30"
maxWait="10000" />
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
因JBOSS和TOMCAT獲取數(shù)據(jù)源連接的方式不同,又修改了獲取連接的代碼,啟動之后是可以運行,頁面讀取數(shù)據(jù)正常,但寫入數(shù)據(jù)庫時,出現(xiàn)了亂碼,我嘗試著修改寫入數(shù)據(jù)庫的SQL語句的編碼,但不管怎么修改都不能正常顯示,后來試著通過URL直接修改連接的編碼試試,于是把TOMCAT數(shù)據(jù)源配置里的URL指定為UTF-8的字符集
url="jdbc:mysql://localhost/app?useUnicode=true&characterEncoding=utf-8"
這里再重新啟動TOMCAT,運行后,數(shù)據(jù)寫入正常,這個困擾我多天的問題終于解決了,之前沒有想到這樣的問題,以為JBOSS里也是用的TOMCAT,在JBOSS里配置的數(shù)據(jù)源都沒有在URL里指定編碼,沒想到單獨使用TOMCAT時會出現(xiàn)這樣的問題,把今天的處理在這里作個記錄,以便以后備查
小結(jié):
當用MYSQL作數(shù)據(jù)庫時,將應用程序從JBOSS遷移到TOMCAT,如果存在亂碼的問題,可以考慮修改URL指定字符集