2010-05-05 23 views
1

我有一個HTML頁面,看起來像:我可以發送POST表單而不是其正文的編碼嗎?

<HTML> 
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'> 
<BODY onload='document.forms[0].submit();'> 
<form name="form" method="post" action="/path/to/some/servlet"> 
<input type="hidden" name="username" value="麗安"> <!-- UTF-8 characters --> 
</form> 
</BODY> 
</HTML> 

正如你所看到的,這個頁面的內容是UTF-8,但我需要用GB2312字符編碼發送,因爲我是在servlet發送此頁面期望從我GB2312。

這是一個有效的場景嗎?因爲在servlet中,我無法使用將字符編碼設置爲GB2312的過濾器來取回這些中文字符!

我創建了一個樣本servlet:

package org.daz; 

import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class EncodingServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    private static final String ENCODING = "GB2312"; 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

     setCharacterEncoding(request, response); 

     String username = request.getParameter("username"); 
     System.out.println(username); 

    } 

    private void setCharacterEncoding(HttpServletRequest request, HttpServletResponse response)throws IOException{ 
     request.setCharacterEncoding(ENCODING); 
     response.setCharacterEncoding(ENCODING); 
    } 

} 

輸出爲:楹��

回答

1

這是不可能的。您需要從頭開始使用GB2312字符,或者將整個應用程序更改爲僅使用UTF-8。您無法將字符編碼X轉換爲字符編碼Y. ASCII範圍之外的任何字符都可能被損壞。

窗體的accept-charset屬性,因爲一些建議被大多數瀏覽器忽略。 W3 spec也字面上聲明「用戶代理可能解釋..」,而不是「必須」。即使如此,它只會用於編碼實際的用戶輸入,而不是像你的例子那樣隱藏的字段。它們已經被編碼在頁面自己的編碼中(在本例中爲GB2312)。換句話說,那些UTF-8字符是已經在頁面被瀏覽器處理的那一刻破壞了。

+0

非常感謝,我在我的博客上評論了這個結論:http://m-hewedy.blogspot.com/2010/05/beware-your-text-editor-encodes-your.html – 2010-05-06 01:50:04

+0

不客氣。我的暱稱是順便** BalusC **,而不是* BlueC *;) – BalusC 2010-05-06 01:58:18

+0

哦,你可能會發現[這篇文章](http://balusc.blogspot.com/2009/05/unicode-how-to-get -characters-right.html),以便在字符和字節的世界中獲得更多的洞察力。 – BalusC 2010-05-06 02:09:05

1

你可以嘗試這樣做,

<form name="form" method="post" action="/path/to/some/servlet" charset="gb2312" accept-encoding="gb2312"> 
<input type="hidden" name="username" value="麗安"> <!-- UTF-8 characters --> 
</form> 

它可能在某些瀏覽器。但是,瀏覽器不需要支持GB2312,因此你的里程可能會有所不同。

+0

我已經試過兩個Firefox和Chrome,而且似乎不是爲我工作! – 2010-05-06 00:55:29

+0

它也取決於操作系統。它適用於中文Windows XP上的IE6。 – 2010-05-06 02:41:02

相關問題