网上搜索到了以下内容,均来自
“有时候我们在处理页面提交过来的中文产生乱码不容易解决时,比如页面选择了别的编码,而 AJAX 是用的 UTF-8
字符集,我们可以对要发送到服务器的中文用 Javascript 的 escape 函数进行编码,然而 Java 中又没有相应的
unescape 函数。
而且 Java 中的 java.net.URLDecoder/java.net.URLEncoder
也对应不上 javascript 的 encodeURI/decodeURI 和
encodeURIComponent/decodeURIComponent 函数。
1. public class EscapeUnescape {
2.
3. public static String escape(String src) {
4. int i;
5. char j;
6. StringBuffer tmp = new StringBuffer();
7. tmp.ensureCapacity(src.length() * 6);
8. for (i = 0; i < src.length(); i++) {
9. j = src.charAt(i);
10. if (Character.isDigit(j) || Character.isLowerCase(j)
11. || Character.isUpperCase(j))
12. tmp.append(j);
13. else if (j < 256) {
14. tmp.append("%");
15. if (j < 16)
16. tmp.append("0");
17. tmp.append(Integer.toString(j, 16));
18. } else {
19. tmp.append("%u");
20. tmp.append(Integer.toString(j, 16));
21. }
22. }
23. return tmp.toString();
24. }
25.
26. public static String unescape(String src) {
27. StringBuffer tmp = new StringBuffer();
28. tmp.ensureCapacity(src.length());
29. int lastPos = 0, pos = 0;
30. char ch;
31. while (lastPos < src.length()) {
32. pos = src.indexOf("%", lastPos);
33. if (pos == lastPos) {
34. if (src.charAt(pos + 1) == 'u') {
35. ch = (char) Integer.parseInt(src
36. .substring(pos + 2, pos + 6), 16);
37. tmp.append(ch);
38. lastPos = pos + 6;
39. } else {
40. ch = (char) Integer.parseInt(src
41. .substring(pos + 1, pos + 3), 16);
42. tmp.append(ch);
43. lastPos = pos + 3;
44. }
45. } else {
46. if (pos == -1) {
47. tmp.append(src.substring(lastPos));
48. lastPos = src.length();
49. } else {
50. tmp.append(src.substring(lastPos, pos));
51. lastPos = pos;
52. }
53. }
54. }
55. return tmp.toString();
56. }
57.
58. public static void main(String[] args) {
59. String tmp = "中文";
60. System.out.println("testing escape : " + tmp);
61. tmp = escape(tmp);
62. System.out.println(tmp);
63. System.out.println("testing unescape :" + tmp);
64. System.out.println(unescape("%u6211%u4eec"));
65. }
66.
对于传送后偶尔会出现乱码的中文字符串用 javascript 的 escape 编码后,传到服务器,就能用上面的方法 unescape 解码了,escape 与 encodeURI 可是不一样的。