为什么说乱码是中国程序员无法避免的话题呢?这个首先要从编码机制上说起,大家都是中文和英文的编码格式不是一样,解码也是不一样的!如果中国的程序员不会遇到乱码,那么只有使用汉语编程。汉语编程是怎么回事我也不大清楚,应该是前年吧,我一朋友给我介绍汉语编程,怎么不错不错?当时因为学习忙没去关注这个,等我闲了,那个朋友不弄这个,问他他也不说不大清楚,最后自己对这个学习也不了了之了。
今天我写这个不是讲解中英文之间的差距,解码等,我是将我在这几年工作遇到各种各样的乱码的解决方法,总结一样,也希望大家能把自己晕倒解决乱码的方法都说出来,咱们弄一个解决乱码的“葵花宝典”。
对于java由于默认的编码方式是 unicode,所以用中文也易出问题,常见的解决是
string s2 = new string(s1.getbytes(“iso-8859-1”),”gbk”);
1、utf8解决jsp中文乱码问题
一般说来在每个页面的开始处,加入:
以下是引用片段:
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<%
request.setcharacterencoding("utf-8");
%>
<%
request.setcharacterencoding("utf-8");
%>
charset=utf-8 的作用是指定jsp向客户端输出的编码方式为“utf-8”
pageencoding="utf-8" 为了让jsp引擎能正确地解码含有中文字符的jsp页面,这在linux中很有效
request.setcharacterencoding("utf-8"); 是对请求进行了中文编码
有时,这样仍不能解决问题,还需要这样处理一下:
string msg = request.getparameter("message");
string str=new string(msg.getbytes("iso-8859-1"),"utf-8");
out.println(st);
2、tomcat 5.5 中文乱码
1)只要把%tomcat安装目录%/ webapps/servlets-examples/web-inf/classes/filters/setcharacterencodingfilter.class文件拷到你的webapp目录/filters下,如果没有filters目录,就创建一个。
2)在你的web.xml里加入如下几行:
3)完成.以下是引用片段:
<filter>
<filter-name>set character encoding</filter-name>
<filter-class>filters.setcharacterencodingfilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gbk</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>set character encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2 get方式的解决办法
1) 打开tomcat的server.xml文件,找到区块,加入如下一行:
uriencoding=”gbk”
完整的应如下:
| 以下是引用片段: <connector port="80" maxthreads="150" minsparethreads="25" maxsparethreads="75" enablelookups="false" redirectport="8443" acceptcount="100" debug="0" connectiontimeout="20000" disableuploadtimeout="true" uriencoding="gbk" /> |
3、xmlhttprequest中文问题
页面jsp用的gbk编码
| 以下是引用片段: 代码 <%@ page contenttype="text/html; charset=gbk"%> javascript部分 代码 function addfracasreport() { var url="controler?actionid=0_06_03_01&actionflag=0010"; var urlmsg="&reportid="+fracasreport1.textreportid.value; //故障报告表编号 var xmlhttp=common.createxmlhttprequest(); xmlhttp.onreadystatechange = common.getreadystatehandler(xmlhttp, eval("turnanalypage")); xmlhttp.open("post",url,true); xmlhttp.setrequestheader( " content-type " , " application/x-www-form-urlencoded); xmlhttp.send(urlmsg); } |
| 以下是引用片段: 代码 public static string utf_8togbk(string str) { try { return new string(str.getbytes("utf-8"), "gbk"); } catch (exception ex) { return null; } } public static string utf8togbk(string str) { try { return new string(str.getbytes("utf-16be"), "gbk"); } catch (exception ex) { return null; } } public static string gbk(string str) { try { return new string(str.getbytes("gbk"),"gbk"); } catch (exception ex) { return null; } } public static string getstr(string str) { try { string temp_p = str; string temp = new string(temp_p.getbytes("iso8859_1"), "gbk"); temp = sqlstrchop(temp); return temp; } catch (exception e) { return null; } } |
4、jdbc odbc bridge的bug及其解决方法
在编写一数据库管理程序时,发现jdbc-odbc bridge存在不易发现的bug。在向数据表插入数据时,如果为英文字符,存储内容完全正确,如果存入中文字符,部分数据库只能存储前七八个中文字符,其他内容被截去,导致存储内容的不完整(有些数据库不存在这个问题,如sybase sql anywhere 5.0。jdbc-odbc bridge还存在无法建表的bug)。
对于广大需要存储中文信息的java程序员来说,这可是一个不好的消息。要么改用其他语言编程,要么选择其他价格昂贵的数据库产品。“一次编写,到处运行”的目标,也大打折扣。能不能采用变通的方法,将中文信息进行处理后再存储来解决这个问题呢?答案是肯定的。
解决问题的具体思路、方法
java采用unicode码编码方式,中英文字符均采用16bit存储。既然存储英文信息是正确的,根据一定规则,将中文信息转换成英文信息后存储,自然不会出现截尾现象。读取信息时再进行逆向操作,将英文信息还原成中文信息即可。由gb2312编码规则可知,汉字一般为二个高位为1的ascii码,在转换时将一个汉字的二个高位1去掉,还原时再将二个高位1加上。为了处理含有英文字符的中文字串,对英文字符则需要加上一个byte 0标记。以下提供的两个公用静态方法,可加入任何一个类中使用。
| 以下是引用片段: 将中英文字串转换成纯英文字串 public static string totureasciistr(string str){ stringbuffer sb = new stringbuffer(); byte[] bt = str.getbytes(); for(int i =0 ;i〈bt.length;i++){ if(bt[i]〈0){ //是汉字去高位1 sb.append((char)(bt[i]&&0x7f)); }else{//是英文字符 补0作记录 sb.append((char)0); sb.append((char)bt[i]); } } return sb.tostring(); } 将经转换的字串还原 public static string untotrueasciistr(string str){ byte[] bt = str.getbytes(); int i,l=0,length = bt.length,j=0; for(i = 0;i〈length;i++){ if(bt[i] == 0){ l++; } } byte []bt2 = new byte[length-l]; for(i =0 ;i〈length;i++){ if(bt[i] == 0){ i++; bt2[j] = bt[i]; }else{ bt2[j] = (byte)(bt[i]|0x80); } j++; } string tt = new string(bt2); return tt; } |
5、solaris下servlet编程的中文问题及解决办法
在使用java开发internet上的一个应用系统时,发现在windows下调试完全正常的servlet,上传到solaris 服务器上,运行却出现故障――返回的网页不能显示中文,应为中文的信息全为乱码;用中文信息做关键字,不能正确检索数据库。后来采用加入检查代码等方法探知故障原因如下:
显示乱码主要是因为通过类 httpservletresponse提供的方法setcontenttype 无法改变返回给客户的数据的编码方式,正确的编码方式应为gb2312或者gbk,而事实上为缺省的iso8859-1。无法检索中文信息则是因为,客户提交的中文信息经浏览器编码到达服务器后,servlet无法将其正确解码。
| 以下是引用片段: 举例说明显示乱码解决方法 servlet 一般通常做法如下: public class zldtestservlet extends httpservlet { public void doget (httpservletrequest request,httpservletresponse response)throws servletexception, ioexception{ //在使用 writer向浏览器返回数据前,设置 content-type header ,在这里设置相应的字符集gb2312 response.setcontenttype("text/html;charset=gb2312"); printwriter out = response.getwriter(); //* // 正式返回数据 out.println("〈html〉〈head〉〈title〉servlet test〈/title〉〈/head〉" ); out.println("这是一个测试页!"); out.println("〈/body〉〈/html〉"); out.close(); } ... } |
printwriter out = new printwriter(new outputstreamwriter(response.getoutputstream(),"gb2312"));
solaris中文信息检索问题的解决
浏览器利用表单向服务器提交信息时,一般采用x-www-form-urlencoded 的mime格式对数据进行编码。如果使用get方法,参数名称和参数值经编码后附加在url后,在java中称作查询串(query string)。
在servlet程序中,如果采用servletrequest的方法getparameter取得参数值,在solaris环境下,对汉字却不能正确解码。因而无法正确检索数据库。
在java 1.2的包――java.net中提供了urlencode和urldecode类。类urlencode提供了按x-www-form-urlencoded格式对给定串进行转换的方法。类urlencode则提供了逆方法。
6、common mail乱码问题
| 以下是引用片段: common mail是一个小而方便的mail包,他实现了对java mail的封装,使用起来十分的方便,但是我在使用他的时候发现,使用纯文本的内容发送,结果是乱码,代码如下: public class testcommonmail { public static void main(string[] args) throws emailexception, messagingexception { simpleemail email = new simpleemail(); email.setcharset("gb2312"); email.sethostname("smtp.163.com"); email.setsubject("test"); email.addto(" test@163.com "); email.setfrom(" test@163.com "); email.setmsg("我的测试"); email.setauthentication("test", "test"); email.send(); } } |
分析了一下commons mail的源码找到了原因。
| 以下是引用片段: 源码如下: public class simpleemail extends email { public email setmsg(string msg) throws emailexception, messagingexception { if (emailutils.isempty(msg)) { throw new emailexception("invalid message supplied"); } setcontent(msg, text_plain); return this; } } email代码片段 public void setcontent(object aobject, string acontenttype) { this.content = aobject; if (emailutils.isempty(acontenttype)) { this.contenttype = null; } else { // set the content type this.contenttype = acontenttype; // set the charset if the input was properly formed string strmarker = "; charset="; int charsetpos = acontenttype.tolowercase().indexof(strmarker); if (charsetpos != -1) { // find the next space (after the marker) charsetpos += strmarker.length(); int intcharsetend = acontenttype.tolowercase().indexof(" ", charsetpos); if (intcharsetend != -1) { this.charset = acontenttype.substring(charsetpos, intcharsetend); } else { this.charset = acontenttype.substring(charsetpos); } } } } email.send();的send方法将调用 public void buildmimemessage() throws emailexception { try { this.getmailsession(); this.message = new mimemessage(this.session); if (emailutils.isnotempty(this.subject)) { if (emailutils.isnotempty(this.charset)) { this.message.setsubject(this.subject, this.charset); } else { this.message.setsubject(this.subject); } } // ======================================================== // start of replacement code if (this.content != null) { this.message.setcontent(this.content, this.contenttype); } // end of replacement code // ======================================================== else if (this.emailbody != null) { this.message.setcontent(this.emailbody); } else { this.message.setcontent("", email.text_plain); } if (this.fromaddress != null) { this.message.setfrom(this.fromaddress); } else { throw new emailexception("sender address required"); } if (this.tolist.size() + this.cclist.size() + this.bcclist.size() == 0) { throw new emailexception( "at least one receiver address required"); } if (this.tolist.size() > 0) { this.message.setrecipients( message.recipienttype.to, this.tointernetaddressarray(this.tolist)); } if (this.cclist.size() > 0) { this.message.setrecipients( message.recipienttype.cc, this.tointernetaddressarray(this.cclist)); } if (this.bcclist.size() > 0) { this.message.setrecipients( message.recipienttype.bcc, this.tointernetaddressarray(this.bcclist)); } if (this.replylist.size() > 0) { this.message.setreplyto( this.tointernetaddressarray(this.replylist)); } if (this.headers.size() > 0) { iterator iterheaderkeys = this.headers.keyset().iterator(); while (iterheaderkeys.hasnext()) { string name = (string) iterheaderkeys.next(); string value = (string) headers.get(name); this.message.addheader(name, value); } } if (this.message.getsentdate() == null) { this.message.setsentdate(getsentdate()); } if (this.popbeforesmtp) { store store = session.getstore("pop3"); store.connect(this.pophost, this.popusername, this.poppassword); } } catch (messagingexception me) { throw new emailexception(me); } } |
由代码可以知道纯文本方式最终调用了java mail的
message.setcontent(this.content, this.contenttype);
content是内容
contenttype是类型,如text/plain,
(我们可以试试直接用java mail发邮件,设置文本内容不使用settext方法,也使用setcontent("测试", "text/plain")方式,你可以看到内容也是乱码)
关键就在于text/plain,我们改成text/plain;charset=gb2312,ok乱码解决了。在commons mail我们看simpleemail 类中setmsg方法调用的就是 setcontent(msg, text_plain);我们只需要将email类中的常量text_plain修改一下加入 charset=你的字符集 ,重新打包jar,这样就可以了 。
7、toad的字符集的设置与oracle的安装
oracle数据库服务器的安装一般是中文字符集,有时安装在不同的平台下,设置为iso编码,toad是oracle开发的最好工具,不是我说的,可是中文环境下安装的toad,打开英文字符的oracle时,中文全是乱码。必须进行设置
环境变量---〉系统变量
加
nls_lang=simplified chinese_china.zhs16gbk
或
nls_lang=american_america.we8iso8859p1
american_america.we8mswin1252
或者
打开注册表,点击hkey_local_mathine
再点击software,再点击oracle
在点击home(oracle所在目录)
在注册表的右半面有nls_lang,
双击它,将你想要的覆盖掉原来的就可以了
最好记下旧的,以便可以改回来。
connect sys/chang_on_install
update props$
set value$='zhs16cgb231280'
where name='nls_characterset';
commit;
这样就ok了
8、如何解决gwt(google web toolkit)中文的问题
gwt 中文乱码解决方法
1.把你要显示的中文“测试字符串”输入到一个文件,如:1.txt
2.进入命令行,进入1.txt所在的目录,敲入以下命令:native2ascii.exe 1.txt 2.txt 回车。这样就生成了另外一个文件2.txt。
3.2.txt的内容如下:/u6d4b/u8bd5/u5b57/u7b26/u4e32
4.然后用上面的编码,在gwt中使用,就可以了.
9、xmlhttp得到的网页怎么是乱码?
(1)在服务器端使用webrequest而不是xmlhttp
(2) 将
streamreader sr = new streamreader(stream);
对于简体中文改成:
streamreader sr = new streamreader(stream , encoding.default );
对于utf-8改成:
streamreader sr = new streamreader(stream , encoding.utf8 );
当然,encoding枚举还有很多其他的成员,对于不同的编码content-type可以有选择的应用
(3)后来我发现无论是content-type是gb2312还是utf-8,用
streamreader sr = new streamreader(stream , encoding.default );
都可以返回正常的汉字,所以统一的改成encoding.default
| 以下是引用片段: 最后,在服务器端从一个url获得网页的源代码的代码如下: /// /// post一个指定的url,获得网页的源代码(用webrequest实现) /// /// /// /// 如果请求失败,返回null /// 如果请求成功,返回网页的源代码 /// public static string getcontentfromurl2( string url ) { //变量定义 string respstr; webrequest mywebrequest=webrequest.create(url); // mywebrequest.preauthenticate=true; // networkcredential networkcredential=new networkcredential( username , password , domain ); // mywebrequest.credentials=networkcredential; // assign the response object of 'webrequest' to a 'webresponse' variable. webresponse mywebresponse=mywebrequest.getresponse(); system.io.stream stream = mywebresponse.getresponsestream(); streamreader sr = new streamreader(stream , encoding.default ); //以字符串形式读取数据流 respstr = sr.readtoend(); sr.close(); return respstr; } |
在web.xml文件中需要配置中文环境。r如下:
| 以下是引用片段: <context-param> <param-name>weblogic.httpd.inputcharset./*</param-name> <param-value>gb2312</param-value> </context-param> |
闽公网安备 35060202000074号