get/post方式的編碼問題解決方案
提交數(shù)據(jù)中文亂碼問題:
-
post提交方式白胀,想不亂碼,只需要設(shè)置request對象的編碼即可
注意:客戶機(jī)數(shù)據(jù)是以哪種編碼提交的,request就應(yīng)該設(shè)什么編碼
程序中設(shè)置request編碼就可控制
request.setCharacterEncoding("UTF-8");
- get提交方式扒寄,設(shè)置request對象的編碼是無效的鱼鼓,用戶想不亂碼,只能手工轉(zhuǎn)換
String data = "??????";//亂碼字符串
byte source[]= data.getBytes("iso8859-1");//得到客戶機(jī)提交的原始數(shù)據(jù)
data = new String(source,"UTF-8");//解決亂碼
等同于(開發(fā)中常用)
data= new String(data.getBytes("iso8859-1","UTF-8"));
- get方式亂碼该编,還可以通過改變服務(wù)器的配置實(shí)現(xiàn)
注:開發(fā)中不建議使用改服務(wù)器的方式解決亂碼問題
查看tomcat7的配置文件中的*** HTTP Connector***迄本,我們可以看到下面這些信息
Attribute | Description |
---|---|
URIEncoding | This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used. |
useBodyEncodingForURI | This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false. |
注解:
URIEncoding:上面的意思是說URL編碼如果未被指定,將使用默認(rèn)(缺省的)ISO-8859-1 編碼
useBodyEncodingForURI:useBodyEncodingForURI默認(rèn)值是"false",如果修改成"true",那么程序中設(shè)置(request設(shè)置編碼)何種編碼方式课竣,URL就以何種編碼解碼嘉赎。
修改tomcat服務(wù)器的配置文件
1.打開配置文件*\tomcat\conf\server.xml
大概在70行左右會有下面的代碼
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
方法一:修改URIEncoding(添加該屬性即可)
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
方法二:修改useBodyEncodingForURI(添加該屬性即可)
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" useBodyEncodingForURI="true"/>
程序中設(shè)置request編碼就可控制
request.setCharacterEncoding("UTF-8");
- 超鏈接方式帶中文數(shù)據(jù)過來,亂碼的問題解決
通過鏈接(html文件)傳值過來比如
<a href="/day06/servlet/RequestDemo6?name=中國">戳我</a>
這種傳值方式是get方式
URL規(guī)定:URL地址后面如果跟了中文數(shù)據(jù)于樟,一定要經(jīng)過URL編碼
html文件這樣沒法處理公条,如果這樣寫需要成jsp頁面