一:form在前臺以post方式提交數據:
瀏覽器將數據(假設為“中國”)發送給服務器的時候,將數據變成0101的二進制數據(假設為98 99)時必然要查碼表,瀏覽器以哪個碼表打開網頁,瀏覽器就以哪個碼表提交數據。數據到達服務器后,數據(98 99)要封裝到request中,在servlet中調用Request的getParameter方法返回的是字符串(“中國”),方法內部拿到數字后要轉成字符,一定要查碼表,由于request的設計者是外國人,所以默認查的是他們常用的ISO8859-1,這就是請求數據產生亂碼的根源。
package com.yyz.request;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//以post方式提交表單
public class RequestDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//請求數據的中文亂碼問題
request.setCharacterEncoding("UTF-8");//客戶端網頁我們控制為UTF-8
String username = request.getParameter("username");
//獲取數據正常,輸出數據時可以查閱不同碼表
response.setCharacterEncoding("gb2312");//通知服務器發送數據時查閱的碼表
response.setContentType("text/html;charset=gb2312");//通知瀏覽器以何種碼表打開
PrintWriter out = response.getWriter();
out.write(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
二:form在前臺以get方式提交數據:
get方式提交的數據依然是瀏覽器用什么碼表打開就用什么碼表發送。不同的是,以get方式提交數據時,request設置編碼無效。即使設置了UTF-8還是會去查ISO8859-1。得到(? ?),要解決這個問題,需要拿著(??)反向查ISO8859-1,拿到(98 99)后,再去查正確碼表。
package com.yyz.request;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//以get方式提交表單
public class RequestDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//請求數據的中文亂碼問題
request.setCharacterEncoding("UTF-8");//以get方式提交數據時,request設置編碼無效。即使設置了UTF-8還是會去查ISO8859-1
String username = request.getParameter("username");
System.out.println(username);
byte source [] = username.getBytes("iso8859-1");
username = new String (source,"UTF-8");
System.out.println(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
三:提交數據中文亂碼問題總結:
1.如果提交方式為post,想不亂碼,只需要設置request對象的編碼即可。
注意:客戶機數據是以哪種方式提交的,request就應該設成什么編碼。
2.如果提交方式為get,設置request對象的編碼是無效的,想不亂碼,只能手工轉換。
String data = "???????";//亂碼字符串
byte source [] = data.getBytes("iso8859-1");//得到客戶機提交的原始數據
data = new String (data.getBytes("iso8859-1"),"UTF-8");//解決亂碼
//等同于
data = new String (source,"UTF-8");
3.get方式的亂碼,還可以通過更改服務器配置的方式實現。更改Tomact的conf目錄下的server.xml文件。
3.1
這種方式并不推薦,因為更改了服務器且并不靈活。
3.2
這么設置后,request的setCharacterEncoding設置什么編碼,連接器就用什么編碼,雖然比上一種更改靈活,但依然會導致我們的應用程序牢牢依賴于服務器,也不被推薦。
四:最后的最后,提一個小細節:URL地址后面如果跟了中文數據,一定要經過URL編碼。表單提交的參數有中文數據,瀏覽器會自動幫我們編碼,但如果是通過鏈接直接帶中文參數,瀏覽器是不會幫我們編碼的,這時想通過上述第二種方式解決中文亂碼問題就時靈時不靈了,應該通過URLEncoding.encode(,"UTF-8")先編碼。