在項目中遇到這樣的問題,客戶的資源文件(比如XML)中有中文名,
而訪問的時候,帶中文名的URL報404.
比如:http://localhost:8080/ProjectTest/cms/版權.xml
在IE地址欄直接輸入也不行。
解決方法:
1. 要讓帶中文名的文件在IE地址欄可以直接訪問,跟代碼是沒關係的,要改Tomcat設置。
Tomcat\conf\server.xml:在8080端口最後添加URIEncoding="UTF-8"即可
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" />
2. 光是改了Tomcat,程序中還是訪問不了,需要用URLEncoder.encode(string, "UTF-8")轉碼
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("http://localhost:8080" + encodeUrlToUTF8(request.getParameter("xml")));
public static String encodeUrlToUTF8(String url) throws UnsupportedEncodingException{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < url.length(); i++) {
String s = url.substring(i, i + 1);
byte[] bytes = s.getBytes("UTF-8");
// 中文字符是2個字節,符號和英文爲1個字節
if (bytes.length == 1) {
if (bytes[0] == ' ')
sb.append("%20");
else
sb.append(s);
} else {
sb.append(URLEncoder.encode(s, "UTF-8"));
}
}
return sb.toString();
}
補充一下我對編碼設置的理解:
如果資源裏面有中文,則需要改成UTF-8或者GBK等類型。
Tomcat服務器既然設置了UTF-8的編碼格式,則傳給他的URL也必須是UTF-8格式,不然讀不到。
一開始我以爲web.xml中,有了下面的過濾器以後,會自動轉換爲UTF-8
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
事實證明,在IE地址欄裏面輸入http://localhost:8080/ProjectTest/cms/版權.xml,確實會自動轉換爲UTF-8。提交給服務器的URL如下:
http://localhost:8080/ProjectTest/cms/%E7%89%88%E6%9D%83.xml
說明web.xml的過濾器起了作用。
但是從代碼裏面直接讀取資源的時候
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("http://localhost:8080" + encodeUrlToUTF8(request.getParameter("xml")));
如果沒有encodeUrlToUTF8手動轉換爲UTF-8的話,它直接會去讀取服務器上http://localhost:8080/ProjectTest/cms/版權.xml這個文件,
Tomcat服務器以UTF-8來讀取當然就讀不到了。
所以web.xml中的設置對於代碼讀取文件似乎並不起作用,因此才需要手動在代碼中轉換。