天天看點

web 亂碼摘抄

JavaWeb--中文亂碼小結 JavaWeb--中文亂碼小結

0.純粹html亂碼:

換個editor吧(有時候notepad都比sublime_text好用),最好是在<head></head>之間添加<meta

charset="utf-8">

1.jsp到jsp之間,表單

(假設包含表單的頁面為a,送出的action為b)

get:不亂碼

post:亂碼(在b頁面用<%request.setCharacterEncoding("utf-8");%>)

超連結形式的跳轉,如果帶有參數,本質上還是get方法,是以不會亂碼

2.jsp到jsp之間,轉發,轉發參數亂碼(<jsp:forward>+<jsp:param>)

需要在轉發标簽<jsp:forward>之前添加<%request.setCharacterEncoding("utf-8");%>

3.servlet頁面out對象輸出中文,亂碼

在相應的方法中添加response.setContentType("text/hmtl;charset=UTF-8");

4.jsp送出表單到servlet,servlet擷取表單變量亂碼

若表單是post方法:在servlet相應方法中添加request.setCharacterEncoding("UTF-8");

若表單是get方法:在servlet相應方法中添加request.setCharacterEncoding("UTF-8");,

或者用getBytes轉碼并構造新的String,例如;

String username = request.getParameter("username");

String name = new

String(username.getBytes("ISO-8859-1"), "UTF-8");

總結一下:

對于post方法送出的表單,擷取表單資料的頁面都要用request.setCharacterEncoding("UTF-8");

對于get方式送出的表單,擷取表單資料的頁面既可以用request.setCharacterEncoding("UTF-8")

也可以用getBytes()的方法構造新的String;對于使用<jsp:param>傳遞參數的情況,需要在傳遞參

數前設定request.setCharacterEncoding("UTF-8");