java中文亂碼解決之道(八)-----解決URL中文亂碼問題
來源:程序員人生 發(fā)布時間:2015-02-03 09:21:22 閱讀次數(shù):4216次
我們主要通過兩種情勢提交向服務(wù)器發(fā)送要求:URL、表單。而表單情勢1般都不會出現(xiàn)亂碼問題,亂碼問題主要是在URL上面。通過前面幾篇博客的介紹我們知道URL向服務(wù)器發(fā)送要求編碼進(jìn)程實在是實在太混亂了。不同的操作系統(tǒng)、不同的閱讀器、不同的網(wǎng)頁字符集,將致使完全不同的編碼結(jié)果。如果程序員要把每種結(jié)果都斟酌進(jìn)去,是否是太恐怖了?有無辦法,能夠保證客戶端只用1種編碼方法向服務(wù)器發(fā)出要求?
有!這里我主要提供以下幾種方法
1、javascript
使用javascript編碼不給閱讀器插足的機(jī)會,編碼以后再向服務(wù)器發(fā)送要求,然后在服務(wù)器中解碼。在掌握該方法的時候,我們需要料及javascript編碼的3個方法:escape()、encodeURI()、encodeURIComponent()。
escape
采取SIO Latin字符集對指定的字符串進(jìn)行編碼。所有非ASCII字符都會被編碼為%xx格式的字符串,其中xx表示該字符在字符集中所對應(yīng)的16進(jìn)制數(shù)字。例如,格式對應(yīng)的編碼為%20。它對應(yīng)的解碼方法為unescape()。

事實上escape()不能直接用于URL編碼,它的真正作用是返回1個字符的Unicode編碼值。比如上面“我是cm”的結(jié)果為%u6211%u662Fcm,其中“我”對應(yīng)的編碼為6211,“是”的編碼為662F,“cm”編碼為cm。
注意,escape()不對"+"編碼。但是我們知道,網(wǎng)頁在提交表單的時候,如果有空格,則會被轉(zhuǎn)化為+字符。服務(wù)器處理數(shù)據(jù)的時候,會把+號處理成空格。所以,使用的時候要謹(jǐn)慎。
encodeURI
對全部URL進(jìn)行編碼,它采取的是UTF⑻格式輸出編碼后的字符串。不過encodeURI除ASCII編碼外對1些特殊的字符也不會進(jìn)行編碼如:! @ # $& * ( ) = : / ; ? + '。

encodeURIComponent
把URI字符串采取UTF⑻編碼格式轉(zhuǎn)化成escape格式的字符串。相對encodeURI,encodeURIComponent會更加強(qiáng)大,它會對那些在encodeURI()中不被編碼的符號(; / ? : @ & = + $ , #)統(tǒng)統(tǒng)會被編碼。但是encodeURIComponent只會對URL的組成部份進(jìn)行個別編碼,而不用于對全部URL進(jìn)行編碼。對應(yīng)解碼函數(shù)方法decodeURIComponent。
固然我們1般都是使用encodeURI方來進(jìn)行編碼操作。所謂的javascript兩次編碼后臺兩次解碼就是使用該方法。javascript解決該問題有1次轉(zhuǎn)碼、兩次轉(zhuǎn)碼兩種解決方法。
1次轉(zhuǎn)碼
javascript轉(zhuǎn)碼:
var url = '<s:property value="webPath" />/ShowMoblieQRCode.servlet?name=我是cm';
window.location.href = encodeURI(url);
轉(zhuǎn)碼后的URL:http://127.0.0.1:8080/perbank/ShowMoblieQRCode.servlet?name=%E6%88%91%E6%98%AFcm
后臺處理:
String name = request.getParameter("name");
System.out.println("前臺傳入?yún)?shù):" + name);
name = new String(name.getBytes("ISO⑻859⑴"),"UTF⑻");
System.out.println("經(jīng)過解碼后參數(shù):" + name);
輸出結(jié)果:
前臺傳入?yún)?shù):??????cm
經(jīng)過解碼后參數(shù):我是cm
2次轉(zhuǎn)碼
javascript
var url = '<s:property value="webPath" />/ShowMoblieQRCode.servlet?name=我是cm';
window.location.href = encodeURI(encodeURI(url));
轉(zhuǎn)碼后的url:http://127.0.0.1:8080/perbank/ShowMoblieQRCode.servlet?name=%25E6%2588%2591%25E6%2598%25AFcm
后臺處理:
String name = request.getParameter("name");
System.out.println("前臺傳入?yún)?shù):" + name);
name = URLDecoder.decode(name,"UTF⑻");
System.out.println("經(jīng)過解碼后參數(shù):" + name);
輸出結(jié)果:
前臺傳入?yún)?shù):E68891E698AFcm
經(jīng)過解碼后參數(shù):我是cm
filter
使用過濾器,過濾器LZ提供兩種,第1種設(shè)置編碼,第2種直接在過濾器中進(jìn)行解碼操作。
過濾器1
該過濾器是直接設(shè)置request的編碼格式的。
public class CharacterEncoding implements Filter {
private FilterConfig config ;
String encoding = null;
public void destroy() {
config = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
//獲得配置參數(shù)
String str = config.getInitParameter("encoding");
if(str!=null){
encoding = str;
}
}
}
配置:
<!-- 中文過濾器的配置 -->
<filter>
<filter-name>chineseEncoding</filter-name>
<filter-class>com.test.filter.CharacterEncoding</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf⑻</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>chineseEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
過濾器2
該過濾器在處理方法中將參數(shù)直接進(jìn)行解碼操作,然后將解碼后的參數(shù)重新設(shè)置到request的attribute中。
public class CharacterEncoding implements Filter {
protected FilterConfig filterConfig ;
String encoding = null;
public void destroy() {
this.filterConfig = null;
}
/**
* 初始化
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* 將 inStr 轉(zhuǎn)為 UTF⑻ 的編碼情勢
*
* @param inStr 輸入字符串
* @return UTF - 8 的編碼情勢的字符串
* @throws UnsupportedEncodingException
*/
private String toUTF(String inStr) throws UnsupportedEncodingException {
String outStr = "";
if (inStr != null) {
outStr = new String(inStr.getBytes("iso⑻859⑴"), "UTF⑻");
}
return outStr;
}
/**
* 中文亂碼過濾處理
*/
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 取得要求的方式 (1.post or 2.get), 根據(jù)不同要求方式進(jìn)行不同處理
String method = request.getMethod();
// 1. 以 post 方式提交的要求 , 直接設(shè)置編碼為 UTF⑻
if (method.equalsIgnoreCase("post")) {
try {
request.setCharacterEncoding("UTF⑻");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// 2. 以 get 方式提交的要求
else {
// 取出客戶提交的參數(shù)集
Enumeration<String> paramNames = request.getParameterNames();
// 遍歷參數(shù)集取出每一個參數(shù)的名稱及值
while (paramNames.hasMoreElements()) {
String name = paramNames.nextElement(); // 取出參數(shù)名稱
String values[] = request.getParameterValues(name); // 根據(jù)參數(shù)名稱取出其值
// 如果參數(shù)值集不為空
if (values != null) {
// 遍歷參數(shù)值集
for (int i = 0; i < values.length; i++) {
try {
// 回圈順次將每一個值調(diào)用 toUTF(values[i]) 方法轉(zhuǎn)換參數(shù)值的字元編碼
String vlustr = toUTF(values[i]);
values[i] = vlustr;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// 將該值以屬性的情勢藏在 request
request.setAttribute(name, values);
}
}
}
// 設(shè)置響應(yīng)方式和支持中文的字元集
response.setContentType("text/html;charset=UTF⑻");
// 繼續(xù)履行下1個 filter, 無1下個 filter 則履行要求
chain.doFilter(request, response);
}
}
配置:
<!-- 中文過濾器的配置 -->
<filter>
<filter-name>chineseEncoding</filter-name>
<filter-class>com.test.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>chineseEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其他
1、設(shè)置pageEncoding、contentType
<%@ page language="java" contentType="text/html;charset=UTF⑻" pageEncoding="UTF⑻"%>
2、設(shè)置tomcat的URIEncoding
在默許情況下,tomcat服務(wù)器使用的是ISO⑻859⑴編碼格式來編碼的,URIEncoding參數(shù)對get要求的URL進(jìn)行編碼,所以我們只需要在tomcat的server.xml文件的<Connector>標(biāo)簽中加上URIEncoding="utf⑻"便可。
-----原文出自:http://cmsblogs.com/?p=1526,請尊重作者辛苦勞動成果,轉(zhuǎn)載說明出處.
-----個人站點:http://cmsblogs.com
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈