技术开发 频道

解析Java WEB中文乱码问题根源



    3.1. 一个真实的转换过程

    经常听到某人说“我这个String是GB2312的”,实际上,String对象永远是Unicode。JVM要处理这些数据,首先从外部的IO流读取字节数据,然后将其还原为String对象。

    举例来说,用户用http表单提交的数据中的“中”字,会用六个ISO8859-1字符表示:%D6%D0。注意这里的D6是两个字符,而不是十六进制的数字!他们的作用正是要代表D6 和 D0两个十六进制的数字。
当应用程序用request.getParameter来读取数据的时候,Tomcat处理字符转换大致是这样的原理(实际的处理过程当然决非这么简单,因为tomcat要考虑性能可靠性等因素)

import java.io.UnsupportedEncodingException; public class ConvertHttp2String { public static void main(String[] args) throws UnsupportedEncodingException { byte[] input = { 0x25, 0x44, 0x36, 0x25, 0x44, 0x30 }; System.out.println("http协议提交的数据为:" + new String(input, "ISO-8859-1")); // 1 转换为16进制数,应该有两个16进制数 byte[] code = new byte[2]; for (int i = 0; i <= 1; i++) { String temp = new String(input, i * 3, 3, "ISO-8859-1"); // 去掉百分号 temp = temp.substring(1, 3); // 计算字符代表的16进制数 code[i] = (byte) Integer.parseInt(temp, 16); } // 2 创建字符串,第一个参数为数据,第二个参数为编码类型 String result = new String(code, "GB2312"); System.out.println("代表字符串:" + result); } }
    输出结果:
    http协议提交的数据为:%D6%D0
    代表字符串:中
0
相关文章