码迷,mamicode.com
首页 > 其他好文 > 详细

处理Servlet响应中文乱码

时间:2017-05-22 11:05:07      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:iso   back   clipboard   output   round   中文乱码   ext   pad   set   

首先,response返回有两种,一种是字节流outputstream,一种是字符流printwrite。

申明:这里为了方便起见,所有输出都统一用UTF-8编码。

先说字节流,要输出“中国",给输出流的必须是转换为utf-8的“中国”,还要告诉浏览器,用utf8来解析数据

 

[html] view plain copy
  1.        //这句话的意思,是让浏览器用utf8来解析返回的数据  
  2.         response.setHeader("Content-type", "text/html;charset=UTF-8");  
  3.         String data = "中国";  
  4.         OutputStream ps = response.getOutputStream();  
  5.         //这句话的意思,使得放入流的数据是utf8格式  
  6.         ps.write(data.getBytes("UTF-8"));  



 

再说字符流,要输出中国,需要设置response.setCharacterEncoding("UTF-8");

 

[html] view plain copy
  1.              //这句话的意思,是让浏览器用utf8来解析返回的数据  
  2. response.setHeader("Content-type", "text/html;charset=UTF-8");  
  3. //这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859  
  4. response.setCharacterEncoding("UTF-8");  
  5. String data = "中国";  
  6. PrintWriter pw = response.getWriter();  
  7. pw.write(data);  

 

 

 

经验:

    1,如果中文返回出现??字符,这表明没有加response.setCharacterEncoding("UTF-8");这句话。

           2,如果返回的中文是“烇湫”这种乱码,说明浏览器的解析问题,应该检查下是否忘加response.setHeader("Content-type", "text/html;charset=UTF-8");这句话。

 

如果上面都解决不了,请看更详细的说明

http://blog.csdn.NET/kontrol/article/details/7767983

处理Servlet响应中文乱码

标签:iso   back   clipboard   output   round   中文乱码   ext   pad   set   

原文地址:http://www.cnblogs.com/datapool/p/6888283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!