解決中文亂碼

來源:互聯網
上載者:User

在基於JAVA的編程中,經常會碰到漢字的處裡及顯示的問題,比如一大堆亂碼或問號。這是因為JAVA中預設的編碼方式是UNICODE,而中國人通常使用的檔案和DB都是基於GB2312或者BIG5等編碼,故會出現此問題。本文抽取了UFO中的示範執行個體來介紹如何解決中文亂碼問題, UFO是www.gm365.com發布的一個web server軟體(以建設網站的穩定性和高負載能力,快速的響應速度和低CPU消耗的功能而開發)。

1、解決jsp中文亂碼問題
    在jsp中,當使用out.print(request.getParameter("parameter-name"))輸出表單資料時,如果表單資料為中文字元時,則輸出的內容是亂碼。引起中文亂碼的原因是,在預設情況下,提取表單資料使用的編碼格式為UTF-8.為瞭解決中文亂碼問題,首先要使用 ISO-8859-1 編碼格式將表單資料存放區到位元組數組中,然後再使用藉助 gb2312的編碼格式將位元組數群組轉換為字串。完整的處理表單的程式碼如下:

例如:我們要將使用者提交的表單資料輸入到頁面,直接用如下方法將會在parameter-name為中文字元時出現亂碼
<%
String pName =request.getParameter("parameter-name");
out.println(pName);
%>
需要對其做如下改動可解決此類中文字元亂碼問題:
<%
String pName =request.getParameter("parameter-name");
byte[] bytesStr=pName.getBytes("ISO-8859-1");
out.println(new String(bytesStr,"gb2312"));
%>

2、如何處理servlet中的中文字元亂碼問題(以jsp檔案調用servlet為例來示範如何處理中文字元)

ioFileServlet.jsp (此jsp檔案用來寫入檔案、提交給servlet檔案ioFileServlet來處理)

<%@ page contentType="text/html;charset=GB2312" %>
<script language="javascript">
 function on_submit()
 {//驗證資料的合法性
  if (form1.file_content.value == "")
    {
     alert("檔案內容不可為空,請輸入檔案內容!");
     form1.file_content.focus();
     return false;
    }
 }
</script>
<HTML>
<head>
<title>提交檔案內容</title>
</head>
<BODY>
<div align="center">
  <center>
<table border="1">
<tr><td colspan="2" align="center">用servlet處理輸入的檔案內容</td></tr>
<tr>
<tr><td>
<form name="form1" action="servlet/readdata/ioFileServlet" method="post" onsubmit="return on_submit()">
  請輸入檔案內容:
</td><td>
<textarea rows="7" name="file_content" cols="52"></textarea>
  </td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="提交"></td></tr>
</form>
</table>
  </center>
</div>
</html>

servlet檔案ioFileServlet的原始碼:
ioFileServlet.java

package readdata;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ioFileServlet extends HttpServlet

 public String codeToString(String str)
  {//處理中文字串的函數
    String s=str;
    try
      {
      byte tempB[]=s.getBytes("ISO-8859-1");
      s=new String(tempB);
      return s;
  }
  catch(Exception e)
    {
    return s;
    }
  }
  public void init(ServletConfig config) throws ServletException
    {
      super.init(config);
    }
  public  void  doPost(HttpServletRequest request,HttpServletResponse response)
                        throws ServletException,IOException
    {
       //設定mime
       response.setContentType("text/html;charset=GB2312");
       PrintWriter out=response.getWriter();
       out.println("<HTML><head><title>接收新使用者註冊</title></head><BODY>");
       //把提交的檔案內容寫入檔案
       int RowSize=30;//檔案每行的字元數
       String tempString1=null;
       String tempString2=null;
       tempString1=codeToString(request.getParameter("file_content"));
       if(tempString1!=null)
       {
         File tempFile1=new File("d:/fileContent.txt");
         FileWriter outfile1=new FileWriter(tempFile1,true);
         BufferedWriter outbuffer1=new BufferedWriter(outfile1);
         int writeStringLength=tempString1.length();
         for(int i=0;i<writeStringLength/RowSize+1;i++)
         {
           if((i+1)*20<writeStringLength)
           {
             tempString2=tempString1.substring(i*RowSize,(i+1)*RowSize);
           }
           else
           {
             tempString2=tempString1.substring(i*RowSize,writeStringLength);
           }
           outbuffer1.write(tempString2);
           outbuffer1.newLine();
         }
         outbuffer1.flush();
         outbuffer1.close();
         outfile1.close();
        }
       out.println("寫入的檔案內容是:<br>");
       //從檔案中讀取內容
       File f=new File("d:/fileContent.txt");
       if(f.exists())
       { 
         FileReader fileReader1=new FileReader(f);
         BufferedReader buffer1=new BufferedReader(fileReader1);
         byte bufferArray[]=new byte[90];
         String tempString=null;
         while((tempString=buffer1.readLine())!=null)
         {
           out.println(tempString+"<br>");
         }
         buffer1.close();
         fileReader1.close();
       }
       else
       {
         out.println("故事中暫時沒有內容。");
       }
       out.println("</body> </html>");
    }
}

servlet功能用來接受ioFileServlet.jsp頁面寫入的內容、將其存入d盤根目錄中的fileContent.txt中(如果沒有就建立),最後將寫入到fileContent.txt檔案的所有內容顯示出來。去掉servle處理中文字串的函數、即不對servlet中的中文字串進行處理,寫入檔案的內容將顯示亂碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.