JavaWeb开发之PrintWriter乱码

PrintWriter 输出信息乱码

  异步方式,返回json给前台时,向前台输出信息使用PrintWriter,但是在输出的过程中,出现乱码的情况。

于是我想起来response.setCharacterEncoding("utf-8");设置页面编码,以及response.setContentType("text/html; charset=utf-8");设置内容类型编码,但是在实验后不成功,乱码依旧。

1
2
3
4
5
6
PrintWriter out = response.getWriter();
response.setCharacterEncoding( "utf-8" );
response.setContentType( "text/html; charset=utf-8" );
out.print(json);
out.flush();
out.close();

 返回的json如下:

1
{ "seriesData" :[22619,22671,21908,5415,0], "caption" : "组织机构代码-年度统计" , "xAxisData" :[ "2010年度" , "2011年度" , "2012年度" , "2013年度" , "2014年度" ]}

 经检查,发现PrintWriter会先获取项目的 编码,根据编码来自己设定characterEncoding,所以得在获取这个PrintWriter对象之前设置编码。如下:注意顺序。

1
2
3
4
5
6
7
  
response.setCharacterEncoding( "utf-8" );
  response.setContentType( "text/html; charset=utf-8" );
  PrintWriter out = response.getWriter();
     out.print(json);
     out.flush();
     out.close();


转自:https://www.cnblogs.com/lucky2u/p/3807931.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值