分類: IT綜合技術javascript
對於Java因爲默認的編碼方式是 UNICODE,因此用中文也易出問題,常見的解決是
String s2 = new String(s1.getBytes(「ISO-8859-1」),」GBK」);
前三種方法是我比較經常使用的方法,別人的經驗告訴我:一般get方法經過改server.xml解決,
post方法經過過濾器或者設置字符集解決,呵呵,不知道是否可行!
一、utf8解決JSP中文亂碼問題
通常說來在每一個頁面的開始處,加入:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
%>
charset=UTF-8 的做用是指定JSP向客戶端輸出的編碼方式爲「UTF-8」
pageEncoding="UTF-8" 爲了讓JSP引擎能正確地解碼含有中文字符的JSP頁面,這在LINUX中頗有效
request.setCharacterEncoding("UTF-8"); 是對請求進行了中文編碼
有時,這樣仍不能解決問題,還須要這樣處理一下:
String msg = request.getParameter("message");
String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8");
out.println(st);
二、Tomcat 5.5 中文亂碼(利用tomcat已經寫好的字符集過濾器)
1)只要把%TOMCAT安裝目錄%/ webappsservlets-examplesWEB-INFclassesfiltersSetCharacterEncodingFilter.class 文件拷到你的webapp目錄/filters下,若是沒有filters目錄,就建立一個。
2)在你的web.xml里加入以下幾行:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、 get方式的解決辦法(修改tomcat server.xml,可是不建議使用的說)
1) 打開tomcat的server.xml文件,找到區塊,加入以下一行:
URIEncoding=」GBK」
完整的應以下:
<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true"
URIEncoding="GBK"
/>
四、xmlHttpRequest中文問題
頁面jsp用的GBK編碼
<%@ page contentType="text/html; charset=GBK"%>
javascript部分
function addFracasReport() {
var url="controler?actionId=0_06_03_01&actionFlag=0010";
var urlmsg="&reportId="+fracasReport1.textReportId.value; //故障報告表編號
var xmlHttp=Common.createXMLHttpRequest();
xmlHttp.onreadystatechange = Common.getReadyStateHandler(xmlHttp, eval("turnAnalyPage"));
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded);
xmlHttp.send(urlmsg);
}
後臺java中得到的reportId是亂碼,不知道該怎麼轉,主要是不知道xmlHttp.send(urlmsg); 之後是什麼編碼?在後面用java來轉,試了幾種,都沒有成功,其中有:
public static String UTF_8ToGBK(String str) {
try {
return new String(str.getBytes("UTF-8"), "GBK");
} catch (Exception ex) {
return null;
}
}
public static String UTF8ToGBK(String str) {
try {
return new String(str.getBytes("UTF-16BE"), "GBK");
} catch (Exception ex) {
return null;
}
}
public static String GBK(String str) {
try {
return new String(str.getBytes("GBK"),"GBK");
} catch (Exception ex) {
return null;
}
}
public static String getStr(String str) {
try {
String temp_p = str;
String temp = new String(temp_p.getBytes("ISO8859_1"), "GBK");
temp = sqlStrchop(temp);
return temp;
} catch (Exception e) {
return null;
}
}
五、Solaris下Servlet編程的中文問題及解決辦法
在使用Java開發Internet上的一個應用系統時,發如今Windows下調試徹底正常的Servlet,上傳到Solaris 服務器上,運行卻出現故障——返回的網頁不能顯示中文,應爲中文的信息全爲亂碼;用中文信息作關鍵字,不能正確檢索數據庫。後來採用加入檢查代碼等方法探知故障緣由以下:
顯示亂碼主要是由於經過類 HttpServletResponse提供的方法setContentType 沒法改變返回給客戶的數據的編碼方式,正確的編碼方式應爲GB2312或者GBK,而事實上爲缺省的ISO8859-1。沒法檢索中文信息則是由於,客戶提交的中文信息經瀏覽器編碼到達服務器後,Servlet沒法將其正確解碼。
舉例說明顯示亂碼解決方法
Servlet 通常一般作法以下:
public class ZldTestServlet extends HttpServlet {
public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
//在使用 Writer向瀏覽器返回數據前,設置 content-type header ,在這裏設置相應的字符集gb2312
response.setContentType("text/html; charset=gb2312");
PrintWriter out = response.getWriter(); //*
// 正式返回數據
out.println("〈html〉〈head〉〈title〉Servlet test〈/title〉〈/head〉" );
out.println("這是一個測試頁!");
out.println("〈/body〉〈/html〉");
out.close();
}
...
}
解決頁面顯示亂碼問題,需將*處代碼換成以下內容:
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"gb2312"));
Solaris中文信息檢索問題的解決
瀏覽器利用表單向服務器提交信息時,通常採用x-www-form-urlencoded 的MIME格式對數據進行編碼。若是使用get方法,參數名稱和參數值經編碼後附加在URL後,在Java中稱做查詢串(query string)。
在Servlet程序中,若是採用ServletRequest的方法getParameter取得參數值,在Solaris環境下,對漢字卻不能正確解碼。於是沒法正確檢索數據庫。
在Java 1.2的包——java.net中提供了URLEncode和URLDecode類。類URLEncode提供了按x-www-form-urlencoded格式對給定串進行轉換的方法。類URLEncode則提供了逆方法。
六、Common Mail亂碼問題
common mail是一個小而方便的mail包,他實現了對Java Mail的封裝,使用起來十分的方便,可是我在使用他的時候發現,使用純文本的內容發送,結果是亂碼,代碼以下:
public class TestCommonMail {
public static void main(String[] args) throws EmailException, MessagingException {
SimpleEmail email = new SimpleEmail();
email.setCharset("GB2312");
email.setHostName("smtp.163.com");
email.setSubject("test");
email.addTo("test@163.com");
email.setFrom("test@163.com");
email.setMsg("個人測試");
email.setAuthentication("test", "test");
email.send();
}
}
分析了一下commons mail的源碼找到了緣由。源碼以下:
public class SimpleEmail extends Email
{
public Email setMsg(String msg) throws EmailException, MessagingException
{
if (EmailUtils.isEmpty(msg))
{
throw new EmailException("Invalid message supplied");
}
setContent(msg, TEXT_PLAIN);
return this;
}
}
Email代碼片斷
public void setContent(Object aObject, String aContentType)
{
this.content = aObject;
if (EmailUtils.isEmpty(aContentType))
{
this.contentType = null;
}
else
{
// set the content type
this.contentType = aContentType;
// set the charset if the input was properly formed
String strMarker = "; charset=";
int charsetPos = aContentType.toLowerCase().indexOf(strMarker);
if (charsetPos != -1)
{
// find the next space (after the marker)
charsetPos += strMarker.length();
int intCharsetEnd =
aContentType.toLowerCase().indexOf(" ", charsetPos);
if (intCharsetEnd != -1)
{
this.charset =
aContentType.substring(charsetPos, intCharsetEnd);
}
else
{
this.charset = aContentType.substring(charsetPos);
}
}
}
}
email.send(); 的send方法將調用
public void buildMimeMessage() throws EmailException
{
try
{
this.getMailSession();
this.message = new MimeMessage(this.session);
if (EmailUtils.isNotEmpty(this.subject))
{
if (EmailUtils.isNotEmpty(this.charset))
{
this.message.setSubject(this.subject, this.charset);
}
else
{
this.message.setSubject(this.subject);
}
}
// ========================================================
// Start of replacement code
if (this.content != null)
{
this.message.setContent(this.content, this.contentType);
}
// end of replacement code
// ========================================================
else if (this.emailBody != null)
{
this.message.setContent(this.emailBody);
}
else
{
this.message.setContent("", Email.TEXT_PLAIN);
}
if (this.fromAddress != null)
{
this.message.setFrom(this.fromAddress);
}
else
{
throw new EmailException("Sender address required");
}
if (this.toList.size() + this.ccList.size() + this.bccList.size() == 0)
{
throw new EmailException(
"At least one receiver address required");
}
if (this.toList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.TO,
this.toInternetAddressArray(this.toList));
}
if (this.ccList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.CC,
this.toInternetAddressArray(this.ccList));
}
if (this.bccList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.BCC,
this.toInternetAddressArray(this.bccList));
}
if (this.replyList.size() > 0)
{
this.message.setReplyTo(
this.toInternetAddressArray(this.replyList));
}
if (this.headers.size() > 0)
{
Iterator iterHeaderKeys = this.headers.keySet().iterator();
while (iterHeaderKeys.hasNext())
{
String name = (String) iterHeaderKeys.next();
String value = (String) headers.get(name);
this.message.addHeader(name, value);
}
}
if (this.message.getSentDate() == null)
{
this.message.setSentDate(getSentDate());
}
if (this.popBeforeSmtp)
{
Store store = session.getStore("pop3");
store.connect(this.popHost, this.popUsername, this.popPassword);
}
}
catch (MessagingException me)
{
throw new EmailException(me);
}
}
由代碼能夠知道純文本方式最終調用了Java Mail的
message.setContent(this.content, this.contentType);
content是內容
contentType是類型,如text/plain,
(咱們能夠試試直接用Java mail發郵件,設置文本內容不使用setText方法,也使用setContent("測試", "text/plain")方式,你能夠看到內容也是亂碼)
關鍵就在於text/plain,咱們改爲text/plain; charset=gb2312,ok亂碼解決了。在commons mail咱們看SimpleEmail 類中setMsg方法調用的就是 setContent(msg, TEXT_PLAIN); 咱們只須要將Email類中的常量TEXT_PLAIN修改一下加入 charset=你的字符集 ,從新打包jar,這樣就能夠了
七、toad的字符集的設置與oracle的安裝
oracle數據庫服務器的安裝通常是中文字符集,有時安裝在不一樣的平臺下,設置爲ISO編碼,toad是oracle開發的最好工具,不是我說的,但是中文環境下安裝的toad,打開英文字符的oracle時,中文全是亂碼。必須進行設置
環境變量---〉系統變量
加
NLS_lANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK
或
NLS_lANG=AMERICAN_AMERICA.WE8ISO8859P1
AMERICAN_AMERICA.WE8MSWIN1252
或者
打開註冊表,點擊HKEY_LOCAL_MATHINE
再點擊Software,再點擊ORACLE
在點擊HOME(ORACLE所在目錄)
在註冊表的右半面有NLS_LANG,
雙擊它,將你想要的覆蓋掉原來的就能夠了
最好記下舊的,以即可以改回來。
connect sys/chang_on_install
update props$
set value$='ZHS16CGB231280'
where name='NLS_CHARACTERSET';
commit;
這樣就OK了
八、如何解決GWT(google web toolkit)中文的問題
GWT 中文亂碼解決方法
1.把你要顯示的中文「測試字符串」輸入到一個文件,如:1.txt
2.進入命令行,進入1.txt所在的目錄,敲入如下命令:native2ascii.exe 1.txt 2.txt 回車。這樣就生成了另一個文件2.txt。
3.2.txt的內容以下:u6d4bu8bd5u5b57u7b26u4e32
4.而後用上面的編碼,在gwt中使用,就能夠了.
九、xmlHttp獲得的網頁怎麼是亂碼?
(1)在服務器端使用WebRequest而不是xmlHttp
(2) 將
StreamReader sr = new StreamReader(stream);
對於簡體中文改爲:
StreamReader sr = new StreamReader(stream , Encoding.Default );
對於utf-8改爲:
StreamReader sr = new StreamReader(stream , Encoding.UTF8 );
固然,Encoding枚舉還有不少其餘的成員,對於不一樣的編碼content-type能夠有選擇的應用
(3)後來我發現不管是content-type是gb2312仍是utf-8,用
StreamReader sr = new StreamReader(stream , Encoding.Default );
均可以返回正常的漢字,因此統一的改爲Encoding.Default
--------------------------------------------------------------------------------
最後,在服務器端從一個url得到網頁的源代碼的代碼以下:
/// <summary>
/// post一個指定的url,得到網頁的源代碼(用WebRequest實現)
/// </summary>
/// <param name="url"></param>
/// <returns>
/// 若是請求失敗,返回null
/// 若是請求成功,返回網頁的源代碼
/// </returns>
public static string GetContentFromUrl2( string url )
{
//變量定義
string respstr;
WebRequest myWebRequest=WebRequest.Create(url);
// myWebRequest.PreAuthenticate=true;
// NetworkCredential networkCredential=new NetworkCredential( username , password , domain );
// myWebRequest.Credentials=networkCredential;
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse=myWebRequest.GetResponse();
System.IO.Stream stream = myWebResponse.GetResponseStream();
StreamReader sr = new StreamReader(stream , Encoding.Default );
//以字符串形式讀取數據流
respstr = sr.ReadToEnd();
sr.Close();
return respstr;
}html