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