在Servlet中利用response向客户端浏览器输出中文时有时会遇到乱码问题,总结如下:
response输出流有两种,一是以字节流输出,一是以字符流输出。
一、以字节流输出:
1.默认编码输出木有乱码
2.通过response的setHeader方法设置编码utf-8,无乱码
3.通过response的setContentType方法设置编码utf-8,无乱码
4.输出数字建议以字符串形式输出
二、以字符流输出:
1.默认查iso-8859-1码表(SUN的Servlet规范要求的) ,客户端显示乱码
2.通过response的setHeader方法设置编码utf-8,无乱码
3.通过response的setContentType方法设置编码utf-8,无乱码
字节流以默认编码输出:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 以字节流用默认编码向客户端输出中文数据,木有乱码
response.setContentType("text/html");
String str = "喔呵呵呵呵";
OutputStream out = response.getOutputStream();
out.write("</br></br><div align=\"center\" style=\"font-size:25px; color:red\">".getBytes());
out.write(str.getBytes());
out.write("</div>".getBytes());
out.close();
}
字节流设置编码为utf-8输出:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 通知客户端查UTF-8码表
response.setContentType("text/html;charset=utf-8");
// 或者:
// response.setHeader("Content-Type","text/html;charset=utf-8");
String str = "喔哈哈哈哈";
OutputStream out = response.getOutputStream();
out.write("</br></br><div align=\"center\" style=\"font-size:25px; color:red\">".getBytes());
out.write(str.getBytes("utf-8"));
out.write("</div>".getBytes());
out.close();
}
字节流输出数字:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Content-Type", "text/html;charset=utf-8");
int i = 98;
OutputStream out = response.getOutputStream();
out.write("</br></br><div align=\"center\" style=\"font-size:25px; color:red\">"
.getBytes());
// out.write(i); 会输出字母b
// 输出数字98
out.write((i + "").getBytes());
out.write("</div>".getBytes());
out.close();
}
字符流设置编码为utf-8输出:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 通知客户端查UTF-8码表
response.setContentType("text/html;charset=utf-8");
// 或者:
// response.setHeader("Content-Type", "text/html;charset=utf-8");
String str = "喔嘿嘿嘿嘿";
PrintWriter out = response.getWriter();
out.write("</br></br><div align=\"center\" style=\"font-size:25px; color:red\">");
out.write(str);
out.write("</div>");
out.flush();
out.close();
}