Servlet中請求與響應的編碼總結
阿新 • • 發佈:2019-02-02
request請求過程 與respone響應過程亂碼問題的產生過程
request域預設使用iso8859-1編解碼,前臺頁面傳遞的引數的編碼型別由html編碼決定,例如html或者jsp使用utf-8編碼,引數傳到request域,request使用iso8859-1解碼,這時候再用getParameter()就出現編解碼不一致,所以出現亂碼。
使用request,客戶端向後臺傳遞資料時 中文亂碼的解決請求方式是 post 資料封裝在請求體中
request.setCharacterEncoding(“utf-8”);
request.getParameter("username");//該方法可以獲得請求體和請求頭的資料
請求方式是 get 資料封裝在請求行中--url裡?username="張三"&password="123"
String name=request.getParameter("username");
先用iso編碼 在用uft-8解碼----這種方法也可以用在請求體中
bytes[ ]buff=name.getBytes("iso8859-1");
name = new String(buff,"utf-8");
response編碼解決
response.setContentType("text/html;charset=UTF-8");
response.getWriter().writer("我是漢字")
括號內有兩個引數,第一個代表響應檔案的MIME型別,例如是mp3對應的MIME型別,瀏覽器核心就知道傳遞過來的MP3型別,第二個是響應檔案的編碼格式。在response.getWrite().write之前要設定它。