异步方式,返回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(); |