上次写了一篇关于midlet登陆程序面向对象的一些内容,这次把以前找到的相关的资料和大家分享下。这里主要讲midlet通过http访问servlet,进而访问oracle过程中的一些中文处理问题。
当能过线线程传中文参数到sevlet 时,需要先把String 转换成unicode 接收时逆运算, 同样的道理,servlet要返回中文字符,线程接收也要经过这两步操作.所以midlet 和服务器端都要有这两个转换函数. 另外,我在查询数据库时发现oracle客户端显示的就是乱码,也就是说当servlet把转换过的中文字符与数据库中的中文匹配时是不成功的,所以要通过一种转换使得string类型数据变为数据库中相同的字体集.我这里用的是非曲直String convert = new String(para.getBytes("GB2312"),"ISO-8859-1"); 这样就可以用中文查询了,同样的道理,查出来的若是中文,也必须能过new String(para.getBytes("ISO-8859-1"),"GB2312");转换过来,然后再通过String2unicode() 传给线程!
两个函数如下,记不清是转载哪位高手的了:
public static String unicode2string(String s)//
{
if (s==null) return null;
StringBuffer result = new StringBuffer();
int i,tempI,j,ch;
for(i =0;i<s.length();i++)
{
if((ch=s.charAt(i))=='//')
{
tempI=i;
i+=2;
while(s.length()>i&&s.charAt(i)=='u')
{
i++;
}
if(s.length()>=i+4)
{
ch=Integer.parseInt(s.substring(i,i+4),16);
i+=3;
}
else
{
i=tempI;
}
}
result.append((char)ch);
}
return result.toString();
}//转换编码!
public static String string2unicode(String s)
{
if (s==null) return null;
StringBuffer result = new StringBuffer();
int i,tempI,j,ch;
for(i =0;i<s.length();i++)
{
if(s.charAt(i)>=0x2018)
{
result.append('//');
result.append('u');
String hex = Integer.toHexString(s.charAt(i));
result.append(hex);
}
else
{
result.append(s.charAt(i));
}
}
return result.toString();
}