一、爲什麼會出現亂碼示意圖:
二、發生中文亂碼有三種情況
1,表單form
(1) post方法提交請求
解決方案
servlet接收端:request.setCharacterEncoding(“utf-8”);//gbk gb2312
(2) get方法提交請求
解決方案:
servlet端寫一個工具類:
public class MyTools {
public static String getNewString(String str){
String newString="";
try {
newString= new String(str.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newString;
}
}
在Servlet中進行調用:
String u=request.getParameter("username");
System.out.println("u="+MyTools.getNewString(u));
2, 鏈接發生亂碼
http://www.sohu.com?name=函數”>測試
解決方案:
該方法和get處理方法一樣
3, sendRedirect發生亂碼
response.sendRedirect(“Servlet地址?username=張三”);
解決方案:
該方法和get處理方法一樣
特別說明:如果你的瀏覽器是ie6或一下版本,則我們的2和3 中情況會出現亂碼(當中文是奇數的時候)
解決方法是:
例如:
發送頁面用URLEncoder進行編碼
String info=java.net.URLEncoder.encode(“你好嗎.jpg”,”utf-8”);
out.println("<a href='/test/loginServlet' username='"+ info +"'>用戶名</a>");
servlet接收端:
request.getParameter("username").getBytes("iso-8859-1","gbk");
說明:我們應當儘量使用post方式提交。
4,在response的時候一般我們通過
response.setContentType(“text/html;charset=utf-8”);
三、sendRedirect和forward區別
(1)叫法不同
sendRedirect()重定向轉發,forward()叫轉向
(2)實際發生的位置不一樣
sendRedirect 發生瀏覽器轉發2次
forward 發生web服務器轉發1次
(3) 用法不一樣
Request.getRequestDispatcher(“/資源URL”),forword(request,response);
Response.sendRedirect(“/web應用/資源URL”);
(4) 能夠去URL範圍不一樣
sendRedirect:可以去任何URL
forward:只能去當前的WEB應用的資源
注意:(1)使用forword不能轉發到該web應用的Url。
因爲forward是發生在web服務器,使用的是同一個request和response
(2)使用sendRedirect()方法不能通過request.setAttribute()把屬性傳遞給下一個Servlet,request.setAttribute():只允許一次請求有效。