1. 程式人生 > >get方式傳值中文亂碼

get方式傳值中文亂碼

問題描述:

  • 點選超連結,則傳值到servlet中,在servelt中通過request.getParameter("bname"); 獲取到的中文字元都顯示為“?“

解決方法:

  1. 方法一: get方式提交的引數編碼,只支援iso8859-1編碼。因此,如果裡面有中文。在後臺就需要轉換編碼,如下
    String bname = request.getParameter("bname");
    bname = new String(bname .getBytes("iso8859-1"),"utf-8");

    前提是你頁面編碼就是utf-8,如果是gbk,那上面那句程式碼後面就改成gbk。
    But修改後我的問題仍沒解決,繼續。。。

  2. 方法二:在客戶端使用 URLEncoder.encode(“中文”,”UTF-8”)對中文引數進行編碼,在伺服器端需要進行解碼this.setName(java.net.URLDecoder.decode(name, “UTF-8”));
    比較麻煩!

  3. 方法三:修改tomcat的server.xml檔案:

    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true"/>

  • 新增URIEncoding="UTF-8" useBodyEncodingForURI="true"這一句。我使用的tomcat8,之前沒有新增useBodyEncodingForURI="true",所以還是亂碼,新增後問題解決!