Struts+Mysql+Tomcat5.0.28+mysql-connector-java-3.0.16-ga-bin.jar 國際化亂碼解決方案

來源:互聯網
上載者:User
國際化的東西帶來的問題還真的好多,各國語言不同,所使用的字元集都不一樣,JAVA,Mysql,Tomcat,瀏覽器等等用的字元集也不一樣,這幾天氣得我都說了好幾次不用什麼Struts,Mysql,Tomcat了,全部都是自己寫出來好了,用統一的編碼統一的字元集,可惜能力不夠,說說而已,問題還是得解決。在網上查了好久,自己也實踐了好多天,問題終於算是解決了。
        因為要考慮到很多國的語言,一開始就把項目立足於國際化,在把串連方式從Struts串連池改為Tomcat的串連池之後,原來我遇到的亂碼有
    1、資源檔裡讀出來在頁面上的亂碼;
    2、資料庫讀出來的亂碼
    3、資料庫寫進去的亂碼
    4、在ActionForm驗證不通過Errors返回的亂碼,也就是request,IE參數傳遞的亂碼了。
    5、有一個JS寫的時間選擇跳出框,如果在charset=UTF-8的時候就出錯,但如果我改為charset=GBK或GB2312時就一切正常了,很奇怪的現象,我還找不出答案來。
        哇,好多的亂碼。。。。頭都大了好幾天。
        下面是我的解決方案
    1、資源檔裡讀出來在頁面上的亂碼:這個最容易解決了,把寫好的ApplicationResources.properties檔案,在DOC底下用 native2ascii -encoding gb2312 ApplicationResources.properties 
ApplicationResources_zh_CN.properties 命令來個字元編碼轉換,將原來的中文轉為Unicode編碼就搞定了中文簡體,繁體也用同樣的命令,只是把 bg2312 改為 bgk 就可以了。
    2、資料庫讀寫的亂碼,剛開始的時候因為受以前的SQL Server+JDBC 影響(在那時寫入資料庫是可以不用做什麼工作的,只是在讀出來的時候來個 gbk = new String(iso.getBytes("ISO-8859-1"), "GBK") 轉換就行了)我也都在把讀寫都在轉換,搞得好複雜也很麻煩,後來在串連池串連代碼jdbc:mysql://localhost:3306/database?autoReconnect=true&useUnicode=true&characterEncoding=GBK那裡加上一個&useUnicode=true&characterEncoding=GBK,保證了在資料庫操作時候使用了統一的編碼字元集,又解決了兩個亂碼問題,一舉兩得,嘿嘿。
    4、request,response的亂碼在網上找了好久,也有兩個解決的辦法,也是來個轉換,還有種辦法是寫一個過濾器,我選擇了後者,因為簡單:),這方法用到兩個檔案,一個是 filter ,一個是 web.xml 檔案,代碼在後面。
    5、至於JS的這個問題,還沒辦法,只好在JSP頁面上改為<%@ page contentType=“text/html; charset=GBK“%>了,反正這樣也沒問題。
        到此為止,亂碼問題總算告一段落了,感覺蠻不錯的,鬱悶了這麼久,終於可以高興了好大一段子了。

-------------------------------------------------------------------------------------------------------------------
過濾器使用代碼:EncodingFilter.java

package com.***.***.***;

import javax.servlet.*;
import java.io.IOException;

/**
 * <p>Filter that sets the character encoding to be used in parsing the
 * incoming request, either unconditionally or only if the client did not
 * specify a character encoding.  Configuration of this filter is based on
 * the following initialization parameters:</p>
 * <ul>
 * <li><strong>encoding</strong> - The character encoding to be configured
 *     for this request, either conditionally or unconditionally based on
 *     the <code>ignore</code> initialization parameter.  This parameter
 *     is required, so there is no default.</li>
 * <li><strong>ignore</strong> - If set to "true", any character encoding
 *     specified by the client is ignored, and the value returned by the
 *     <code>selectEncoding()</code> method is set.  If set to "false,
 *     <code>selectEncoding()</code> is called <strong>only</strong> if the
 *     client has not already specified an encoding.  By default, this
 *     parameter is set to "true".</li>
 * </ul>
 *
 * <p>Although this filter can be used unchanged, it is also easy to
 * subclass it and make the <code>selectEncoding()</code> method more
 * intelligent about what encoding to choose, based on characteristics of
 * the incoming request (such as the values of the <code>Accept-Language</code>
 * and <code>User-Agent</code> headers, or a value stashed in the current
 * user's session.</p>
 *
 */
public class EncodingFilter 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

WEB.XML檔案:將下面的代碼放在WEB.xml檔案的<display-name>下面就行了
    <filter>
       <filter-name>encodingFilter</filter-name>
       <display-name>EncodingFilter</display-name>
       <description>Set the request encoding</description>
       <filter-class>com.voip.admin.util.EncodingFilter</filter-class>
       <init-param>
         <param-name>encoding</param-name>
         <param-value>GB18030</param-value>
      </init-param>
      <init-param>
         <param-name>ignore</param-name>
         <param-value>true</param-value>
      </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.