無為

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

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            190 Posts :: 291 Stories :: 258 Comments :: 0 Trackbacks

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

          1、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);

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

          1)只要把%TOMCAT安裝目錄%/ webapps\servlets-examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.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>


          3、 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"
          />

          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; //故障報告表編號
          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;
          }
          }



          5、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則提供了逆方法。

          6、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,這樣就可以了

          7、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了

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

          GWT 中文亂碼解決方法

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

          9、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;

          }



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

          posted on 2007-09-10 17:58 草兒 閱讀(3881) 評論(0)  編輯  收藏 所屬分類: JAVA WEB應用
          主站蜘蛛池模板: 贡觉县| 察雅县| 睢宁县| 湟中县| 台湾省| 广德县| 青田县| 简阳市| 峨山| 天台县| 南澳县| 梁河县| 油尖旺区| 云安县| 图木舒克市| 忻城县| 镇平县| 田东县| 铜陵市| 抚顺县| 温州市| 竹北市| 五指山市| 云霄县| 固原市| 汤阴县| 崇礼县| 高要市| 台湾省| 梅河口市| 同仁县| 汾西县| 双牌县| 贞丰县| 额济纳旗| 金乡县| 望谟县| 洛南县| 若羌县| 河津市| 凉城县|