ajax servlet 乱码引起的思考

      本来自己是写前端的,但为了帮人家做课程设计,就跑去学了一下JSP了!快完成的时候遇到了一件很郁闷的事情,就是servlet返回数据给ajax的时候乱码,都是“?????”,太郁闷了,就一直上网查,很多的意见是加上就OK了!

response.setHeader("Content-Type", "text/xml ; charset=utf-8");
response.setCharacterEncoding("text/xml ; charset=utf-8");

      情况一:我就加上去吧,可是依然???,郁闷了,为什么那么多人都可以我不行呢?先给大家看看我的代码:
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/xml ; charset=utf-8");
response.setCharacterEncoding("text/xml ; charset=utf-8");

      情况二:突然给我在一篇文章中找到一条评论,改了下就OK了,代码为:

response.setHeader("Content-Type", "text/xml ; charset=utf-8");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("text/xml ; charset=utf-8");


      情况三:好奇心一来,发觉问题来了,我再改了一下代码就发觉有异常了,代码为:
response.setHeader("Content-Type", "text/xml ; charset=utf-8");
response.setCharacterEncoding("text/xml ; charset=utf-8");
PrintWriter out = response.getWriter();

      我看了很久,只明白了情况一和二的差别,因为PrintWriter的对象out已经生成了,所以你再修改repose的http头已经没作用了,但情况三到底为什么呢?

      就去查了下api:

PrintWriter getWriter() throws IOException   
Returns a PrintWriter object that can send character text to the client. 
The PrintWriter uses the character encoding returned by getCharacterEncoding().   
If the response's character encoding has not been specified as described in getCharacterEncoding 
(i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1. 

     

       原来PrintWriter生成对象的时候,charactor encoding就默认变为ISO-8859-1的编码,假如情况三是先setCharacterEncoding为utf-8,但最后又变回ISO-8859-1,所以会出错,呵呵!之前跟张志权师兄验证的效果也是这样,只是不明白为啥这样,呵呵,终于真相大白了。发次博客,以明真相,呵呵!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值