Response物件響應的中文亂碼處理
阿新 • • 發佈:2018-12-18
在開發中,我們經常會遇到使用Response物件響應中文,會遇到亂碼,有些人遇到了不知道怎麼處理,會放在那裡不管,我這裡分享下我對於Response物件響應中文亂的碼處理的一些心得吧:
/** * Response響應中文的處理 */ public class ResponseDemo3 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(response); } /** * 使用字元流輸出中文 * @param response * @throws IOException * @throws UnsupportedEncodingException */ private void test2(HttpServletResponse response) throws IOException, UnsupportedEncodingException { // 方法一: // 設定瀏覽器預設開啟的時候採用的字串: // response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 設定response獲得字元流的緩衝區的編碼: // response.setCharacterEncoding("UTF-8"); // 方法二: // 簡化程式碼: response.setContentType("text/html;charset=UTF-8"); response.getWriter().println("中文"); } /** * 使用位元組流輸出中文 * @param response * @throws IOException * @throws UnsupportedEncodingException */ private void test1(HttpServletResponse response) throws IOException, UnsupportedEncodingException { // 使用位元組流的方式輸出中文: ServletOutputStream outputStream = response.getOutputStream(); // 設定瀏覽器預設開啟的時候採用的字符集 response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 設定中文轉成位元組數字字符集編碼 outputStream.write("中文".getBytes("UTF-8")); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }