ServletOutputStream回写页面乱码

一段utf-16的string,整了好多种格式,硬是无法正确输出到页面上:

 

首先尝试了outputstream, 即便指定string-》byte[]的编码,还是出错

 

Java代码   收藏代码
  1. resp.getOutputStream().write(out.getBytes("UTF-16"));  
  2. resp.getOutputStream().print(out);  
  3. resp.getOutputStream().flush();  
  4. resp.getWriter().close();   

然后尝试过Printwriter,均以失败告终。

 

 

借此也搞明白了response回写内容的两个方法:(指上面的writer和outStream)

1.PrintWriter object that can send character text to the client.

2.ServletOutputStream suitable for writing binary data in the response

3.Calling flush() on the xxx  commits the response.

4.Either getOutputStream() or getWriter() may be called to write the body, not both.

 

但是比较诡异的是,为什么这两种方式(指上面的writer和outStream)会出现乱码呢?

再看看编码解析的过程:

uses the character encoding returned by getCharacterEncoding().

  首先使用response对象的getCharacterEncoding(),如果没有设置,则默认编码方式都为ISO-8859-1

 

那么问题也就明确了,在输入流指定正确的编码之后,还需要配合response的编码参数,否则读出来解析就乱码

 

正解

Java代码   收藏代码
  1. //方式1  
  2. resp.setCharacterEncoding("UTF-16");  
  3. resp.getWriter().print(out);  
  4. resp.getWriter().flush();  
  5. resp.getOutputStream().close();  
  6.   
  7. //方式2  
  8. resp.setCharacterEncoding("UTF-16");  
  9. resp.getOutputStream().write(out.getBytes("UTF-16"));  
  10. resp.getOutputStream().flush();  
  11. resp.getOutputStream().close();  

 

 再或者,包装一层: 

 

Java代码   收藏代码
  1. ServletOutputStream out2 = resp.getOutputStream();   
  2. OutputStreamWriter ow = new OutputStreamWriter(out2,"UTF-16");   
  3. ow.write(out);   
  4. ow.flush();   
  5. ow.close();   

 


来源:ITeye

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值