Mysql與JSP網頁中文亂碼問題的解決方案

自從以前學習JSP開始,中文亂碼問題就一直不斷,苦不堪言。這次在項目開始之前,我們要解決的第一個問題就是把mysql的中文亂碼問題搞定。經過多天的努力,終於成功的解決了中文亂碼問題,特寫在這裏,以備後用。

軟件及環境:Windows XP(2000), j2sdk1.4.2, Tomcat 5.0.25, mysql 4.1, EMS Mysql Manager 2(方便建表,版本2.8.5.1),驅動爲mysql-connector-java-3.1.4-beta-bin.jar。

目標:在該環境下,實現中文的正常顯示,讀取與插入數據庫。

注:我只在此環境下測試通過,別的系統及不同版本未測試

要點:統一字符集(JSP頁面編碼,mysql建庫時字符集選擇,連接數據庫URL,request設定等)

下面我以GBK爲例講解。如果要使用utf-8,只要在相應的GBK處換成utf-8即可

--------------------------- 步驟1 以GBK字符集建庫建表 -------------------------------------

我使用EMS來建mysql的數據庫及表,因爲它是圖形界面,方便操作(就像SQL SERVER 2000中的企業管理器一樣)。

建庫時,從EMS菜單中選create Database...新建一個數據庫,CharacterSet選gbk_bin(另一個gbk_chinese_ci不知道與這個有什麼區別,我找資料也沒有找到。如果你知道,請告訴我,我補充在這裏)。不要把工具欄上有一個加號和數據庫模樣的圖標當成新建數據庫了,那個新註冊一個已經存在的數據庫。
後面建表時,也要選擇同樣的字符集。

建好後,此時不要用EMS向裏面插入數據,否則你看到的中文依然是亂碼。

--------------------------- 步驟2 連接數據庫的URL後加些參數 -------------------------------

假設我新建的數據庫是testdb,那麼我連接數據庫的url應該爲:

jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=gbk

此時要注意:如果我是把這個url寫在JAVA代碼中,就直接這樣寫。但如果是在xml配置文件中(如struts-config.xml,web.xml等),要把其中的&改爲&才行,否則會出錯。也就是:

jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=gbk

--------------------------- 步驟3 每個JSP頁面都要聲明該中文字符集 ----------------------------

在每個JSP頁面的最上面都加上一句

<%@ page language="java" contentType="text/html;charset=GBK" %>

這樣才能保證JSP頁面中的中文顯示正常

--------------------------- 步驟4 加一個傳遞參數時設定request字符集的filter類 -----------------------

因爲網絡中字符在傳遞的時候,都是統一以iso-8859-1的編碼傳遞,所以我們必須對request重新設定字符集,才能正常顯示中文。如果採用filter類來實現,我們不用在每次取中文參數時都要重新設定。

filter類的內容:

/*
* ====================================================================
*
* JavaWebStudio 開源項目
*
* Struts_db v0.1
*
* ====================================================================
*/
package com.strutsLogin.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
* 中文過濾器
*/
public class SetCharacterEncodingFilter implements Filter {

// ----------------------------------------------------- Instance Variables

/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;

/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;

/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;

// --------------------------------------------------------- Public Methods

/**
* Take this filter out of service.
*/
public void destroy() {

this.encoding = null;
this.filterConfig = null;

}

/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}

// Pass control on to the next filter
chain.doFilter(request, response);

}

/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;

}

// ------------------------------------------------------ Protected Methods

/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {

return (this.encoding);

}

}//EOC


該代碼來自於www.javawebstudio.com,特此感謝!

然後我們在web.xml中加一些配置,就可以了,配置如下:

<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>javawebstudio.struts_db.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>

放在web.xml的合適位置。一般在最後,<jsp-config>標籤之前(如果有的話)

經過以上步驟,JSP和mysql的中文顯示及插入就都正常了。在STRUTS中也正常。

但是,此時如果你用EMS或mysql的命令行控制檯來看錶中的數據,卻發現它們都是????。這是怎麼回事呢?

不用擔心,只要我們運行下面的這幾行命令,就能看到正常的中文了!

SET character_set_client = gbk;
SET character_set_connection = gbk;
SET character_set_database = gbk;
SET character_set_results = gbk;
SET character_set_server = gbk;

SET collation_connection = gbk_bin;
SET collation_database = gbk_bin;
SET collation_server = gbk_bin;

如果你用的是mysql的命令行,則直接輸入就好。

如果是EMS,則在工具欄中有一個Show SQL Editor按鈕,點一下,把上面的命令輸入,再按一個"execute"的按鈕,就行了!

而且在這種情況下,你可以甚至可以用中文名來建數據庫,表名和字段名!!!!

----------------------------------------------------------------------------------------------------

但是有一點要特別注意!

像GBK,UTF-8這樣的名字,在mysql與JAVA中有不同的規定,寫的時候要格外注意,否則會出錯。

比如GBK,在JAVA中要寫成GBK,但在mysql中要寫成gbk(連接數據庫的URL)

比如UTF-8,在JAVA中要寫成UTF-8,但在Mysql中要寫成utf8

其它的字集符也有類似的區別
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章