1. 程式人生 > >Java 的亂碼解決方法 統一編碼UTF-8 (轉)

Java 的亂碼解決方法 統一編碼UTF-8 (轉)

一、介紹兩個類
URLEncoder//編碼
URLDecoder//解碼


看看下面的測試輸出,你就明白是做什麼的了


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class main {


public static void main(String[] args) throws UnsupportedEncodingException{
System.out.println("UTF-8");
String a = URLEncoder.encode("中文測試", "UTF-8");//編碼
System.out.println(a);
System.out.println(URLDecoder.decode(a,"UTF-8"));//還原
//下面同理
System.out.println("\nGBK(百度就是用這種)");
a = URLEncoder.encode("中文測試", "GBK");
System.out.println(a);
System.out.println(URLDecoder.decode(a,"GBK"));
}
}


[輸出]
UTF-8
%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95
中文測試
GBK(百度就是用這種)
%D6%D0%CE%C4%B2%E2%CA%D4
中文測試


看了上面的輸出就明白百度位址列那一串是什麼了。假如你做了下面一系列設定,那麼在伺服器端你接收到Get方法的中文引數將被轉換成型別%D6%D0%CE%C4%B2%E2%CA%D4 你就需要用到上面的兩個工具類, 如果你像我在下面設定,你在上面的呼叫的第二個引數也得是UTF-8; 使用post就不需要解碼,直接讀取就行了。


二、配置tomcat (這一步我沒有做,但沒發現問題,我用的是Tomcat 5.08經典版本)
開啟tomcat的server.xml檔案,找到區塊,加入如下一行:
URIEncoding="UTF-8"
完整的應如下:
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>





三、增加連線資料庫的引數
mysql 資料庫建表時設定編碼為utf8(寫法不同不是UTF-8),


連線資料庫:
// 連線引數,這裡設定連線使用的編碼
public static final String DB_URL = "jdbc:mysql://localhost:3306/?useUnicode=true&characterEncoding=utf8";





四、使用過濾器設定編碼
1、
// 簡單的就用下面這個,這裡使用的是硬編碼也就是在程式碼中寫死了用那種編碼我這裡用utf-8,也可以把編碼設定用寫到web.xml中的Filter設定中
package com.max;


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;


/**
* Example filter that sets the character encoding to be used in parsing the
* incoming request
*/
public class SetCharacterEncodingFilter implements Filter {


/**
* Take this filter out of service.
*/
public void destroy() {
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {


request.setCharacterEncoding("UTF-8");


// 傳遞控制到下一個過濾器
chain.doFilter(request, response);
}


public void init(FilterConfig filterConfig) throws ServletException {
}
}


web.xml配置檔案中增加
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.max.SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>





2、
//下面這個是將編碼設定放到web.xml中的


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


然後我們在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>UTF-8</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>
<url-pattern>/*</url-pattern>
</filter-mapping>


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





五、在JSP頁面中設定編碼


<%@ page language="java" pageEncoding="UTF-8"%>





六、使用i18n
使ApplicationResources.properties支援中文
建立一個ApplicationResources_ISO.properties檔案,把應用程式用的message都寫進去,然後在dos下執行這個命令,
native2ascii -encoding gb2312 ApplicationResources_ISO.properties ApplicationResources.properties
native2ascii [引數] [輸入檔案] [輸出檔案]


native2ascii這個工具是jdk自帶的一個東東,所以如果path都設定正確就可以直接運行了,你可以在$java_home$/bin下找到他。
轉換後的中文類似於這個樣子
中文格式下 :user_name_label=使用者名稱:
ascii格式下 :user_name_label=\u7528\u6237\u540D\uFF1A


Netbean 有個方便的編輯多國語言的工具,但不是直接寫,而是在彈出視窗中編輯,確定插入後自動轉換成ascii如上面那種.
Eclipse 有個一樣功能的外掛jinto在下面的地址中下載
http://www.guh-software.de/jinto.html


在Jsp頁面使用 "user_name_label" 來引用 "使用者名稱:",而且能夠簡單方便實現多語言支援。


通常將編碼同一成UTF-8是很有好處的,如果想使用其他編碼如GBK,這上面用到UTF-8全改為GBK

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/joe4011/archive/2006/11/15/1386048.aspx