<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" <!-- queryString的編碼規則 --> useBodyEncodingForURI="true" <!-- uri采用utf-8編碼,默認采用iso-8859-1默認編碼,注意uri不包括queryString --> URIEncoding="UTF-8" />
<servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/中文Servlet/index.do</url-pattern> </servlet-mapping>
假如有一個請求的url:http://webapp/中文Servlet/index.do?q=中文參數
訪問這個url會報404沒有找到.設置URIEncoding="UTF-8"才會訪問到這個servlet,因為URIEncoding默認采用iso-8859-1編碼
useBodyEncodingForURI所代表的意思:queryString的編碼規則,也就是get參數編碼規則,不設置這個參數,默認是false,代表采用URIEncoding的編碼,設置為ture,代表采用request.setCharacterEncoding("utf-8")的編碼,如果request.setCharacterEncoding("utf-8")沒有設置,則默認采用iso-8859-1編碼
post中參數默認采用request.setCharacterEncoding("utf-8")中的編碼,如果request.setCharacterEncoding("utf-8")沒有設置,則采用iso-8859-1編碼
綜上所述:
URIEncoding解決帶中文的uri的問題,並不是針對get中文參數的
request.setCharacterEncoding("utf-8")解決的是post中文參數的問題
要解決get中文參數問題,則request.setCharacterEncoding("utf-8"),URIEncoding,useBodyEncodingForURI這3個參數都會影響它,這要分為2種情況:
1.request.setCharacterEncoding("utf-8")設置了,只需設置useBodyEncodingForURI="true"
2.request.setCharacterEncoding("utf-8")沒有設置,只需設置URIEncoding="UTF-8"
一般我們都調用了request.setCharacterEncoding("utf-8"),所以只需要設置useBodyEncodingForURI="true"就行了,這樣就解決了get和post的中文參數問題,至於URIEncoding="UTF-8"是可以不設置的,除非uri中包含了中文,這跟queryString沒有多大關系
瀏覽器如果顯示中文亂碼,則服務器端需要設置response.setCharacterEncoding("utf-8"),並且瀏覽器的編碼設置要與服務器端設置的要一致
參考資料:http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/