兩種解決方式
第1種:代碼里轉換
String name = request.getParamter("name");
String nameUtf8 = new String(name.getBytes("ISO8859-1"), "UTF-8");
第2種:修改Tomcat配置
TOMCAT_HOME/conf/server.xml
....
<!-- 修改前 -->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- 修改后 -->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UFT-8"/>
注意:
百度到的結果一般都是上面這兩種解決方法。
第一種方法太麻煩了,get請求里有十幾個參數,難道都要一個一個的 new String(name.getBytes("ISO8859-1"), "UTF-8");
嗎?這樣的代碼笨重,且修改時不小心就會出錯。
第二種方法很好,但要注意:tomcat7 及以上版本默認都設置了 URIEncoding="UFT-8",不必再去手動設置。這一點,百度到的博客里一個說的都沒有,全都是互相轉載,不知多少年前的了。最好的辦法就是看官方文檔。
我本地和測試環境下get請求參數值中文都是正常的,一到生產就亂碼了,查不到數據。花了兩個多小時后才確定是開發和生產環境不同導致的
查看當前tomcat版本
# 進入 TOMCAT_HOME/bin,執行 version.sh 查看當前tomcat版本
[root@jtdev bin]# sh version.sh
/opt/tomcat9/logs/catalina.out
Using CATALINA_BASE: /opt/tomcat9
Using CATALINA_HOME: /opt/tomcat9
Using CATALINA_TMPDIR: /opt/tomcat9/temp
Using JRE_HOME: /usr/java8/jdk1.8.0_11/jre
Using CLASSPATH: /opt/tomcat9/bin/bootstrap.jar:/opt/tomcat9/bin/tomcat-juli.jar
Server version: Apache Tomcat/9.0.35
Server built: May 5 2020 20:36:20 UTC
Server number: 9.0.35.0
OS Name: Linux
OS Version: 2.6.32-504.el6.x86_64
Architecture: amd64
JVM Version: 1.8.0_11-b12
JVM Vendor: Oracle Corporation
查看官方文檔
TOMCAT_HOME/webapps/docs 目錄下保存的就是當前版本的文檔,當啟動tomcat后,訪問 http://host:port/docs 即可
- 選擇左側Referance菜單欄下的 Configuration,進入配置項說明頁面
- 再選擇左側Connectors菜單欄下的 HTTP/1.X ,進入Connector元素配置項說明
- 全局搜索 URIEncoding
URIEncoding | This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. The default value is UTF-8. |
---|