說明:在計算機中保存的一切文本信息是以一定的編碼表(0,1,0,1)來保存我們所認識的字符(漢字或英文字符),由字符到計算機存儲的二進制過程是編碼,由讀取二進制到文本的過程稱為解碼。而字符編碼有多種不同的編碼表,所以,如果編碼格式和解碼格式不是同一個碼表就會出現亂碼。想要避免出現亂碼,需要使保存和讀取時使用相同的碼表。
在java web編程中經常會出現亂碼,現在詳細講解一下如何進行設置,避免亂碼
1 網頁編碼
在編寫網頁的時候,需要指定網頁的編碼格式,使用<meta http-equiv="content-type" content="text/html; charset=UTF-8">來指定。此時瀏覽器讀取或者發送請求的時候會以指定的編碼格式保存或發送數據。在此是以utf-8形式。
例如代碼片段:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
< form action = "/Pro1/bb" method = "post" > 用戶名: < input type = "text" name = "username" >< br > 性別: 男< input type = "radio" name = "gender" value = "男" > 女< input type = "radio" name = "gender" value = "女" >< br > 喜歡的顏色:< br > 紅< input type = "checkbox" name = "color" value = "紅" > 綠< input type = "checkbox" name = "color" value = "綠" > 藍< input type = "checkbox" name = "color" value = "藍" > < br >來自的國家 < select name = "country" > < option value = "中國" >中國</ option > < option value = "美國" >美國</ option > < option value = "日本" >日本</ option > </ select > < br > < input type = "submit" value = "提交" > < input type = "reset" value = "重置" > </ form > |
2 后端讀取請求數據
在java web的servlet中要想獲取請求的數據,需要將發送過來的二進制數據按照相應的碼表進行解碼才可以獲取相應的人類可以讀懂字符串。這個例子中是使用post方法,所以在處理post請求中,在獲取有中文的請求參數前需要先設置編碼格式,不然會出現亂碼。因為服務器默認使用iso-8859-1編碼表進行解碼。
當然,如果想要在輸出中輸出中文字符,也需要使用統一的字符編碼,此處是utf-8,代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding( "utf-8" ); response.setContentType( "text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); String username = request.getParameter( "username" ); String gender = request.getParameter( "gender" ); String[] colors = request.getParameterValues( "color" ); String country = request.getParameter( "country" ); out.println( "<!DOCTYPE HTML>" ); out.println( "<HTML>" ); out.println( " <HEAD><TITLE>測試servlet</TITLE></HEAD>" ); out.println( " <BODY>" ); out.print( "<h1>以下是您的輸入</h1>" ); out.print( "<p>" ); out.print( "您的用戶名:" +username+ "<br>" ); out.print( "您的性別:" +gender+ "<br>" ); out.print( "您喜歡的顏色:" ); for (String cr:colors){ out.print(cr+ " " ); } out.print( "<br>" ); out.print( "您的國家:" +country+ "<br>" ); out.print( "</p>" ); out.println( " </BODY>" ); out.println( "</HTML>" ); } |
注意:此處的request.setCharacterEncoding("utf-8");只對請求實體的內容有效。post請求參數是存放在請求實體中,get方法的請求參數是放在url的后面以問號開始,‘&'連接多個參數。所以想要獲取get方法的參數,需要使用手動解碼,或者使用filter。
手動解碼方法,為了簡單起見只對性別進行解碼,實際使用中需要對每一個參數進行解碼:String gender = new String(req.getParameter("gender").getBytes("iso-8859-1"),"utf-8") ;
到此時就可以完美解決網頁和服務器端出現漢字亂碼的現象,記住一條,出現亂碼的都是因為編碼和解碼使用不同編碼表的原因,要使用相同的編碼表,即可解決問題。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。