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
 

相關推薦

Java亂碼解決方法 統一編碼UTF-8

一、介紹兩個類URLEncoder//編碼URLDecoder//解碼 看看下面的測試輸出,你就明白是做什麼的了 import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import jav

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

一、介紹兩個類URLEncoder//編碼URLDecoder//解碼看看下面的測試輸出,你就明白是做什麼的了import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.

Java亂碼解決方法 統一編碼 這裡使用UTF-8編碼

一、介紹兩個類 URLEncoder//編碼 URLDecoder//解碼 看看下面的測試輸出,你就明白是做什麼的了 import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.U

MyEclipse解決中文亂碼問題,統一UTF-8,及其他設定

一、workspace 二、jsp 三、content-type 4、resource 5、get傳參亂碼問題 tomcat的server.xml修改以下程式碼 <Connector port="8080" protocol="HTTP/1.1"

idea軟體編碼已經設定好了為utf-8,但是svn中down下來的檔案格式本身不是utf-8的,此時開啟後會出現中文亂碼解決方法

我是個idea的忠實使用者,新公司的專案都是用eclipse做的,通過svn拉下程式碼後發現,註釋的內容裡,中文內容都是亂碼。問過專案負責人,說可能是GBK編碼。 但是,我通過idea的setting設定了編碼,試了5種編碼都沒用,中文內容還是亂碼。最後還是自己試出來解決方案。 詳細的原因請參考

解決excel打開utf-8編碼csv文件亂碼的bug

導入 對話框 原因 識別 直接 格式 excel exce 編碼 直接用 excel 打開 utf-8 編碼的 csv 文件會導致漢字部分出現亂碼。原因是 excel 以 ansi 格式打開,不會做編碼識別。 打開 utf-8 編碼的 csv 文件的方法: 1) 打開

request.getParameter(“引數名”) 中文亂碼解決方法【新手設定問題】【JSP】-表單傳值問題:為什麼設定UTF-8之後還是亂碼

request.getParameter(“引數名”) 中文亂碼解決方法【新手設定問題】【JSP】-表單傳值問題:為什麼設定UTF-8之後還是亂碼? 問題:jsp讀取的value值亂碼;設定UTF-8之後還是亂碼…… 備註:本文是轉載的,題目上增加關鍵詞方便查詢

ANT 編譯警告: 編碼 UTF-8 的不可對映字元解決方法

今天開始學ant自動構建工具。在編譯原始檔的時候碰到一個警告: 9: 警告:編碼 UTF8 的不可對映字元     [javac]  System.out.println("ʹ��jar�ļ����");     [javac]                      

【asp】asp網頁utf-8亂碼解決方法

asp網頁utf8亂碼解決方法: 採用UTF-8編碼,除了要將檔案另存為UTF-8格式之外, 還需要同時指定codepage及charset. 保證asp不會出現utf-8亂碼的程式碼: &

解決 Excel 打開 UTF-8 編碼 CSV 文件亂碼的 BUG

href 編碼 亂碼 coder 原因 ESS targe bug 方法 亂碼恢復 http://www.mytju.com/classcode/tools/messycoderecover.asp 直接用 Excel 打開 UTF-8 編碼的 CSV 文件會導致

VIM顯示utf-8文件亂碼解決方法

1.相關基礎知識介紹         在Vim中,有四個與編碼有關的選項,它們是:fileencodings、fileencoding、encoding和termencoding。在實際使用中,任何一個選項出現錯誤,都會導致出現亂碼。因此,每一個Vim使用者都應該明確這

Java FileWriter無法編碼utf-8 轉換方法

原本想通過檔案追加的方式,向.txt或者.json檔案(其他也類似)結尾新增新的文字,開始通過FileWriter追加,但是中文追加後卻成了亂碼。 查了一圈下來結論是:Java FileWriter

頁面jsp編碼utf-8,傳遞中文引數到java後臺出現亂碼

1、前臺頁面jsp的編碼是contentType=”text/html; charset=utf-8” 後臺編碼是gdk,傳遞中文引數時出現亂碼,後臺接收到傳遞的引數時需要進行轉換才能解決亂碼問題。 new String(this.getParameter(

解決ZendStudio打開utf-8格式的php文件亂碼

英文版 菜單 -s order 產生 pan 要點 php文件 zend 一般php文件都為utf-8無BOM格式的,用zendstudio默認設置打開時中文會產生亂碼,這是因為zendstudio默認設置編碼格式為GBK格式,所以我們這裏需要重新設置其編碼格式,這

Java Web 中 Servlet 中文亂碼解決方法

Servlet中文亂碼問題解決方法 import java.io.*; import java.net.URLEncoder; import javax.servlet.*; import javax

postman請求引數亂碼及Tomcat伺服器設定UTF-8解決方案

使用postman模擬請求,服務端怎麼獲取中文都是亂碼,嘗試設定請求編碼和accept等都沒用。同事提醒下發現在伺服器server.xml對應埠Connector新增URIEncoding=”UTF-8”即可 > <Connect

java後臺傳遞json到前臺 中文亂碼解決方法

查了兩天 都說處理response 不過我搭建的框架裡沒有response(至少表面上沒有) 然後拼接了一個String作為json傳遞到前臺 但是遇到中文 前臺就顯示“?” 試過很多辦法 都不能解決 最後放棄了字串拼接 改為物件傳遞 結果成功了 controller對應方

Ant打包出現 編碼utf-8不可對映字元 的解決辦法

做android開發過程中,用ant打包新建的專案,結果出現"編碼utf-8不可對映字元"的問題,網上的解決辦法說是因為編譯時的編碼和檔案儲存的編碼格式不一致,但是並沒有起作用,最後發現,原因是我建立專

requests包爬取gb2312編碼介面亂碼解決方法

利用chrome控制檯分析一個介面時,發現編碼是gb2312,設定爬蟲encoding=’gb2312’可能會出現亂碼,比如�z ?等,解決方案為設定encoding=’GBK’ import requests r=requests.get('https:

convmv 解決GBK 遷移到 UTF-8 ,中文 檔名亂碼

yum install convmv 命令: convmv -f GBK -t UTF-8 -r --nosmart --notest <目標目錄> -f from -t to --nosmart 如果已經是utf-8 忽略 -r 包含所有子目錄