1. 程式人生 > >客戶端提交資料給伺服器端,如果資料中帶有中文的話,有可能會出現亂碼情況

客戶端提交資料給伺服器端,如果資料中帶有中文的話,有可能會出現亂碼情況

request:

如果是GET方式

程式碼轉碼

String username = request.getParameter("username");

String password = request.getParameter("password");

String username = request.getParameter("username"); String password = request.getParameter("password");
System.out.println("userName="+username+"==password="+password);

//get請求過來的資料,在url位址列上就已經經過編碼了,所以我們取到的就是亂碼,
//tomcat收到了這批資料,getParameter 預設使用ISO-8859-1去解碼

//先讓文字回到ISO-8859-1對應的位元組陣列 , 然後再按utf-8組拼字串
username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
System.out.println("userName="+username+"==password="+password);

 

直接在tomcat裡面做配置,以後get請求過來的資料永遠都是用UTF-8編碼。

可以在tomcat裡面做設定處理 conf/server.xml 加上URIEncoding="utf-8" 

如果是POST方式

request.setCharacterEncoding("UTF-8");

這行設定一定要寫在getParameter之前。

response

以字元流輸出:

//1. 指定輸出到客戶端的時候,這些文字使用UTF-8編碼
    response.setCharacterEncoding("UTF-8");

    //2. 直接規定瀏覽器看這份資料的時候,使用什麼編碼來看。
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.getWriter().write("我愛JAVA...");

以位元組流輸出:

//1. 指定瀏覽器看這份資料使用的碼錶
    response.setHeader("Content-Type", "text/html;charset=UTF-8");

    //2. 指定輸出的中文用的碼錶
    response.getOutputStream().write("我愛JAVA..".getBytes("UTF-8"));

通用:不管是以位元組流輸出還是以字元流輸出

response.setContentType("text/html;charset=UTF-8");
//寫在響應的資料的前面