1. 程式人生 > >【javaweb】HttpServletRequest中文亂碼問題

【javaweb】HttpServletRequest中文亂碼問題

客戶端提交資料給伺服器端,如果資料中帶有中文的話,有可能會出現亂碼情況,那麼可以參照以下方法解決。

* 如果是GET方式
    
    1. 程式碼轉碼
           

 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編碼。 


    

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

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


* 如果是POST方式

        這個說的是設定請求體裡面的文字編碼。
        request.setCharacterEncoding("UTF-8");

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