HttpServletResponse输出的中文乱码问题

首先,response 返回有两种,一种是字节流 outputstream,一种是字符流 printwrite。接下面我从这两方面在解决这个 HttpServletResponse 输出的中文乱码问题。

申明: 这里所有输出都统一用 UTF-8 编码。

  • 字节流 outputstream

  流程:要输出“孤城落寞博客”,给输出流的必须是转换为 utf-8 的“孤城落寞博客”,还要告诉浏览器,用 utf8 来解析数据

1
2
3
4
5
6
7
8
9
/**
 * 设置请求头,告诉浏览器响应的内容是用 UTF-8 编码的 Html
 */
 response.setHeader("Content-type", "text/html;charset=UTF-8");
 String data = "孤城落寞博客";
 /**
  * 放入流的数据是utf8格式
  */
 response.getOutputStream().write(data.getBytes("UTF-8"));
  • 字符流 printwrite

  流程:要输出“孤城落寞博客”,需要设置 response.setCharacterEncoding(“UTF-8”);

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/**
 * 设置请求头,告诉浏览器响应的内容是用 UTF-8 编码的 Html
 */
 response.setHeader("Content-type","text/html;charset=UTF-8");
/**
 *  告诉 Servlet 用UTF-8编码。而不是默认的 IS08859
 */
 response.setCharacterEncoding("UTF-8");
/**
 *  告诉 Servlet 返回的内容是 Html
 */
 String data = "孤城落寞博客";
 PrintWriter pw = response.getWriter().write(data);

常见问题

  • 如果中文返回出现??字符,这表明没有加 response.setCharacterEncoding(“UTF-8”);这句话。
  • 如果返回的中文是“烇湫”这种乱码,说明浏览器的解析问题,应该检查下是否忘加 response.setHeader(“Content-type”, “text/html;charset=UTF-8”);这句话。