在計算機中,隻有二進制的資料,不同字元對應二進制的規則,就是字元的編碼。
常用字元集:Ascii碼;iso8859-1碼;gb2312和gbk;unicode;utf-8;
出現亂碼的解決方案:
1、 以post方法送出的資料中有中文字元, 可以在擷取請求參數值之前,調用request.setCharacterEncoding(“UTF-8”),指定請求正文使用的字元編碼是UTF-8;
2、在向浏覽器發送資料之前調用 response.setHeader("Content-Type", "text/html;charset=UTF-8");這是最好的一種解決方法
3、用OutputStream輸出數字時出現亂碼解決:response.getOutputStream().write((97+"").getBytes()); //97任意數字
4、response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
response.getOutputStream().write("中國".getBytes("UTF-8"))。
當下載下傳以中文名稱的檔案時出現亂碼的解決方案:
設定消息頭
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
//URLEncoder.encode(String,String)方法是:使用指定的編碼機制将字元串轉換為
application/x-www-form-urlencoded
格式。