bufegar 2007-4-6 13:53
中文字符集的一些解决方法 (转)
我们在写JSP程序的时候常常会遇到中文问题, 下面提供一些解决方法:
1.最常用的当然是:
[java]
<%@ page contentType="text/html;charset=GB2312" %>
[/java]
再看看HEAD中是否加入了这个:
[java]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
[/java]
2.还是不行怎么办?自己搞定罗!
[java]
/**
* String >> char[] >> byte[] >> String
* 解决JSP中的中文问题 (转载)
* */
public static String toByteString(String source){
if (source==null) return null;
if (source.length()==0) return "";
char[] chars=source.toCharArray();
byte[] bytes=new byte[source.length()*2];
int index=0;
for (int i=0,charValue=0;i<chars.length&&index<chars.length*2;i++)
{
charValue=(int)chars[i];
if (charValue>255){
try{
byte[] tmp=(new Character(chars[i])).toString().getBytes"GB2312");
for (int j=0;j<tmp.length;j++){
bytes[index]=tmp[j];
index++;
}
}catch(Exception e){
e.printStackTrace();
}
}else{
bytes[index]=(byte)chars[i];
index++;
}
}
return new String(bytes,0,index);
}
[/java]
3.当表单提交的时候也改转一转:
1).转成gb2312
[java]
String str = request.getParameter(“title”);
String tsr = new String(strTitle.getBytes(“8859-1”),”gb2312”);//把Unicode用国标解码
strTitle.getBytes(“8859-1”),”//使用指定的字符集转成unicode
[/java]
2).unicode 和 gb2312转
[java]
//unicode -> 8859-1 charset
public static String to_iso_8859_1(String source){
if (source == null) return null;
try{
String s = new String(source.getBytes(), "iso-8859-1");
return s;
}catch(Exception uee){
String s1 = null;
return s1;
}
}
//8859-1 -> unicode charset
public static String from_iso_8859_1(String source){
if (source == null) return null;
try{
String s = new String(source.getBytes("iso-8859-1"));
return s;
}catch(Exception uee){
String s1 = null;
return s1;
}
}
[/java]