java get 編碼/解碼的處理方法

來源:互聯網
上載者:User

java get 編碼/解碼的處理方法

GET方式訪問URL時參數的編解碼工作:編碼/傳輸/解碼
基本過程:
public static void main(String args[]){
    String tsptString=”中文”;
    //1.編碼(瀏覽器會按網頁的編碼方式進行編碼)
    String tempString=URLEncoder.encode(tsptString,”GBK”);
    //2.傳輸
    System.out.println(tempString);
    //3.解碼(由Tomcat容器按照預設編碼方式自動解碼)
    String resultString=URLDecoder.decode(tempString,”ISO-8859-1”);
    //查看
    System.out.println(resultString);
}
上面的方式會因為編解碼方式的不統一導致亂碼,可以通過下面的方式來統一編碼方式:
1.用戶端指定網頁編碼
    a)   頁面指定GBK方式: submit.jsp教程 中 <%@ page pageEncoding="GBK"%> ,Servelet中Response.setContentType(“text/html; charset=GBK”);
    b)   瀏覽器指定GBK方式:在頁面上右擊->編碼->選擇新編碼->GBK(無法依靠使用者為你的頁面指定編碼,但要預防使用者通過這種方法改變你的編碼方式
 2.服務端改變編碼
   a)   改變Tomcat的預設編碼方式:開啟tomcat下的conf檔案夾下的service.xml尋找8080,添加 URIEncoding='GBK',如下: <Connector port="8080" maxThreads="150" … URIEncoding='GBK' />,執行個體中此時第三步的預設編碼方式就變成了GBK
   b)   不使用TOMCAT的預設編碼方式在伺服器端處理參數,例如在Servlet中
protected void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
    String param=arg0.getParameter("param");
    //UTF-8為指定的頁面編碼方式,ISO-8859-1為TOMCAT的預設解碼方式(URIEncoding)
    param =new String(param.getBytes("ISO-8859-1"),"UTF-8");
    System.out.println(param);
 
    //...
}
3.利用jS兩次編碼
 
String toTspt="中文";
//進行兩次一次編碼,使用js時 可以這樣 var params="name="+URIEncode(URIEncode(valueOfName))+"&age="+...;
String tempString=URLEncoder.encode(URLEncoder.encode(toTspt, "UTF-8"), "UTF-8");
//傳送,瀏覽器不會再進行編碼,因為沒有特殊字元
System.out.println(tempString);
//解析,這裡不管TOMCAT預設的什麼編碼方式都可以正確解碼(沒有特殊字元)
tempString=URLDecoder.decode(tempString,"ISO-8859-1");
//擷取結果
String resultString=URLDecoder.decode(tempString, "UTF-8");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.