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

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

    PrintWriter out = response.getWriter();
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    out.print(json);
    out.flush();
    out.close();

 返回的json如下:

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

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

  
response.setCharacterEncoding("utf-8");
  response.setContentType("text/html; charset=utf-8");
  PrintWriter out = response.getWriter();
    out.print(json);
    out.flush();
    out.close();

 

相关文章:

  • 2021-11-03
  • 2021-08-27
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2021-08-25
  • 2021-07-24
猜你喜欢
  • 2022-12-23
  • 2022-02-06
  • 2021-12-16
  • 2021-10-26
  • 2021-07-21
  • 2021-09-29
  • 2021-08-24
相关资源
相似解决方案