<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    無為

    無為則可為,無為則至深!

      BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
      190 Posts :: 291 Stories :: 258 Comments :: 0 Trackbacks

    對于Java由于默認(rèn)的編碼方式是 UNICODE,所以用中文也易出問題,常見的解決是
    String s2 = new String(s1.getBytes("ISO-8859-1"),"GBK");
    前三種方法是我比較常用的方法,別人的經(jīng)驗(yàn)告訴我:通常get方法通過改server.xml解決,
    post方法通過過濾器或者設(shè)置字符集解決,呵呵,不知道是否可行!

    1、utf8解決JSP中文亂碼問題

    一般說來在每個(gè)頁面的開始處,加入:

    <%@ 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"); 是對請求進(jìn)行了中文編碼

    有時(shí),這樣仍不能解決問題,還需要這樣處理一下:

    String msg = request.getParameter("message");
    String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8");
    out.println(st);

    2、Tomcat 5.5 中文亂碼(利用tomcat已經(jīng)寫好的字符集過濾器)

    1)只要把%TOMCAT安裝目錄%/ webapps\servlets-examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.class 文件拷到你的webapp目錄/filters下,如果沒有filters目錄,就創(chuàng)建一個(gè)。

    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>


    3、 get方式的解決辦法(修改tomcat server.xml,但是不建議使用的說)

    1) 打開tomcat的server.xml文件,找到區(qū)塊,加入如下一行:
    URIEncoding="GBK"
    完整的應(yīng)如下:

    <Connector
    port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    debug="0" connectionTimeout="20000"
    disableUploadTimeout="true"
    URIEncoding="GBK"
    />

    4、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; //故障報(bào)告表編號
    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是亂碼,不知道該怎么轉(zhuǎn),主要是不知道xmlHttp.send(urlmsg); 以后是什么編碼?在后面用java來轉(zhuǎn),試了幾種,都沒有成功,其中有:

    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;
    }
    }



    5、Solaris下Servlet編程的中文問題及解決辦法

    在使用Java開發(fā)Internet上的一個(gè)應(yīng)用系統(tǒng)時(shí),發(fā)現(xiàn)在Windows下調(diào)試完全正常的Servlet,上傳到Solaris 服務(wù)器上,運(yùn)行卻出現(xiàn)故障--返回的網(wǎng)頁不能顯示中文,應(yīng)為中文的信息全為亂碼;用中文信息做關(guān)鍵字,不能正確檢索數(shù)據(jù)庫。后來采用加入檢查代碼等方法探知故障原因如下:

    顯示亂碼主要是因?yàn)橥ㄟ^類 HttpServletResponse提供的方法setContentType 無法改變返回給客戶的數(shù)據(jù)的編碼方式,正確的編碼方式應(yīng)為GB2312或者GBK,而事實(shí)上為缺省的ISO8859-1。無法檢索中文信息則是因?yàn)椋蛻籼峤坏闹形男畔⒔?jīng)瀏覽器編碼到達(dá)服務(wù)器后,Servlet無法將其正確解碼。

    舉例說明顯示亂碼解決方法

    Servlet 一般通常做法如下:

    public class ZldTestServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{

    //在使用 Writer向?yàn)g覽器返回?cái)?shù)據(jù)前,設(shè)置 content-type header ,在這里設(shè)置相應(yīng)的字符集gb2312

    response.setContentType("text/html; charset=gb2312");

    PrintWriter out = response.getWriter(); //*

    // 正式返回?cái)?shù)據(jù)

    out.println("〈html〉〈head〉〈title〉Servlet test〈/title〉〈/head〉" );

    out.println("這是一個(gè)測試頁!");

    out.println("〈/body〉〈/html〉");

    out.close();

    }

    ...

    }

    解決頁面顯示亂碼問題,需將*處代碼換成如下內(nèi)容:

    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"gb2312"));

    Solaris中文信息檢索問題的解決
    瀏覽器利用表單向服務(wù)器提交信息時(shí),一般采用x-www-form-urlencoded 的MIME格式對數(shù)據(jù)進(jìn)行編碼。如果使用get方法,參數(shù)名稱和參數(shù)值經(jīng)編碼后附加在URL后,在Java中稱作查詢串(query string)。

    在Servlet程序中,如果采用ServletRequest的方法getParameter取得參數(shù)值,在Solaris環(huán)境下,對漢字卻不能正確解碼。因而無法正確檢索數(shù)據(jù)庫。

    在Java 1.2的包--java.net中提供了URLEncode和URLDecode類。類URLEncode提供了按x-www-form-urlencoded格式對給定串進(jìn)行轉(zhuǎn)換的方法。類URLEncode則提供了逆方法。

    6、Common Mail亂碼問題

    common mail是一個(gè)小而方便的mail包,他實(shí)現(xiàn)了對Java Mail的封裝,使用起來十分的方便,但是我在使用他的時(shí)候發(fā)現(xiàn),使用純文本的內(nèi)容發(fā)送,結(jié)果是亂碼,代碼如下:

    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方法將調(diào)用
    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);
    }
    }
    由代碼可以知道純文本方式最終調(diào)用了Java Mail的
    message.setContent(this.content, this.contentType);
    content是內(nèi)容
    contentType是類型,如text/plain,
    (我們可以試試直接用Java mail發(fā)郵件,設(shè)置文本內(nèi)容不使用setText方法,也使用setContent("測試", "text/plain")方式,你可以看到內(nèi)容也是亂碼)

    關(guān)鍵就在于text/plain,我們改成text/plain; charset=gb2312,ok亂碼解決了。在commons mail我們看SimpleEmail 類中setMsg方法調(diào)用的就是 setContent(msg, TEXT_PLAIN); 我們只需要將Email類中的常量TEXT_PLAIN修改一下加入 charset=你的字符集 ,重新打包jar,這樣就可以了

    7、toad的字符集的設(shè)置與oracle的安裝

    oracle數(shù)據(jù)庫服務(wù)器的安裝一般是中文字符集,有時(shí)安裝在不同的平臺下,設(shè)置為ISO編碼,toad是oracle開發(fā)的最好工具,不是我說的,可是中文環(huán)境下安裝的toad,打開英文字符的oracle時(shí),中文全是亂碼。必須進(jìn)行設(shè)置

    環(huán)境變量---〉系統(tǒng)變量

    NLS_lANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK

    NLS_lANG=AMERICAN_AMERICA.WE8ISO8859P1

    AMERICAN_AMERICA.WE8MSWIN1252

    或者

    打開注冊表,點(diǎn)擊HKEY_LOCAL_MATHINE
    再點(diǎn)擊Software,再點(diǎn)擊ORACLE
    在點(diǎn)擊HOME(ORACLE所在目錄)
    在注冊表的右半面有NLS_LANG,
    雙擊它,將你想要的覆蓋掉原來的就可以了
    最好記下舊的,以便可以改回來。

    connect sys/chang_on_install
    update props$
    set value$='ZHS16CGB231280'
    where name='NLS_CHARACTERSET';
    commit;
    這樣就OK了

    8、如何解決GWT(google web toolkit)中文的問題

    GWT 中文亂碼解決方法

    1.把你要顯示的中文"測試字符串"輸入到一個(gè)文件,如:1.txt
    2.進(jìn)入命令行,進(jìn)入1.txt所在的目錄,敲入以下命令:native2ascii.exe 1.txt 2.txt 回車。這樣就生成了另外一個(gè)文件2.txt。
    3.2.txt的內(nèi)容如下:\u6d4b\u8bd5\u5b57\u7b26\u4e32
    4.然后用上面的編碼,在gwt中使用,就可以了.

    9、xmlHttp得到的網(wǎng)頁怎么是亂碼?

    (1)在服務(wù)器端使用WebRequest而不是xmlHttp
    (2) 將

    StreamReader sr = new StreamReader(stream);

    對于簡體中文改成:

    StreamReader sr = new StreamReader(stream , Encoding.Default );

    對于utf-8改成:

    StreamReader sr = new StreamReader(stream , Encoding.UTF8 );

    當(dāng)然,Encoding枚舉還有很多其他的成員,對于不同的編碼content-type可以有選擇的應(yīng)用

    (3)后來我發(fā)現(xiàn)無論是content-type是gb2312還是utf-8,用

    StreamReader sr = new StreamReader(stream , Encoding.Default );

    都可以返回正常的漢字,所以統(tǒng)一的改成Encoding.Default




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

    最后,在服務(wù)器端從一個(gè)url獲得網(wǎng)頁的源代碼的代碼如下:



    /// <summary>
    /// post一個(gè)指定的url,獲得網(wǎng)頁的源代碼(用WebRequest實(shí)現(xiàn))
    /// </summary>
    /// <param name="url"></param>
    /// <returns>
    /// 如果請求失敗,返回null
    /// 如果請求成功,返回網(wǎng)頁的源代碼
    /// </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 );
    //以字符串形式讀取數(shù)據(jù)流
    respstr = sr.ReadToEnd();
    sr.Close();

    return respstr;

    }



    凡是有該標(biāo)志的文章,都是該blog博主Caoer(草兒)原創(chuàng),凡是索引、收藏
    、轉(zhuǎn)載請注明來處和原文作者。非常感謝。

    posted on 2007-09-10 17:58 草兒 閱讀(3884) 評論(0)  編輯  收藏 所屬分類: JAVA WEB應(yīng)用
    主站蜘蛛池模板: 免费看黄的成人APP| 成熟女人牲交片免费观看视频 | 亚洲欧洲免费无码| 韩国亚洲伊人久久综合影院| 亚洲毛片不卡av在线播放一区| 国产精品免费观看调教网| 亚洲性色高清完整版在线观看| 国产午夜影视大全免费观看| 日本高清不卡aⅴ免费网站| 91亚洲国产成人久久精品| 亚洲成av人片不卡无码久久| 99免费视频观看| 国内成人精品亚洲日本语音 | 亚洲AV成人一区二区三区在线看| 四虎免费久久影院| 日韩精品无码一区二区三区免费| 亚洲av最新在线观看网址| 国产V亚洲V天堂无码| 在线免费观看污网站| 久久午夜无码免费| 深夜特黄a级毛片免费播放| 亚洲高清不卡视频| 久久久久亚洲AV无码专区桃色| 免费可以看黄的视频s色| 国产成人精品免费视频大全| 亚洲午夜理论片在线观看| 亚洲乱码中文字幕久久孕妇黑人 | 亚洲精品中文字幕无乱码| 亚洲人成网站色在线入口| 无码免费午夜福利片在线| 国产一级黄片儿免费看| 国产精品无码亚洲一区二区三区 | 青柠影视在线观看免费| 丰满亚洲大尺度无码无码专线| 亚洲欧洲高清有无| 亚洲s色大片在线观看| 免费一级做a爰片性色毛片| 动漫黄网站免费永久在线观看 | 无码精品A∨在线观看免费| 国产精品网站在线观看免费传媒| 免费一级毛suv好看的国产网站|