Servlet响应的中文字符集问题

时间:2022-05-08
本文章向大家介绍Servlet响应的中文字符集问题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在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,无乱码

字节流以默认编码输出:

 1 public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         // 以字节流用默认编码向客户端输出中文数据,木有乱码
 4         response.setContentType("text/html");
 5 
 6         String str = "喔呵呵呵呵";
 7         OutputStream out = response.getOutputStream();
 8         out.write("</br></br><div align="center" style="font-size:25px; color:red">".getBytes());
 9 
10         out.write(str.getBytes());
11 
12         out.write("</div>".getBytes());
13         out.close();
14 }

字节流设置编码为utf-8输出:

 1 public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3 
 4         // 通知客户端查UTF-8码表
 5         response.setContentType("text/html;charset=utf-8");
 6 
 7         // 或者:
 8         // response.setHeader("Content-Type","text/html;charset=utf-8");
 9 
10         String str = "喔哈哈哈哈";
11         OutputStream out = response.getOutputStream();
12         out.write("</br></br><div align="center" style="font-size:25px; color:red">".getBytes());
13 
14         out.write(str.getBytes("utf-8"));
15 
16         out.write("</div>".getBytes());
17         out.close();
18 }

字节流输出数字:

 1 public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         response.setHeader("Content-Type", "text/html;charset=utf-8");
 4 
 5         int i = 98;
 6         OutputStream out = response.getOutputStream();
 7 
 8         out.write("</br></br><div align="center" style="font-size:25px; color:red">"
 9                 .getBytes());
10 
11         // out.write(i); 会输出字母b
12 
13         // 输出数字98
14         out.write((i + "").getBytes());
15 
16         out.write("</div>".getBytes());
17         out.close();
18 }

字符流设置编码为utf-8输出:

 1 public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         // 通知客户端查UTF-8码表
 4         response.setContentType("text/html;charset=utf-8");
 5         // 或者:
 6         // response.setHeader("Content-Type", "text/html;charset=utf-8");
 7 
 8         String str = "喔嘿嘿嘿嘿";
 9         PrintWriter out = response.getWriter();
10         out.write("</br></br><div align="center" style="font-size:25px; color:red">");
11 
12         out.write(str);
13 
14         out.write("</div>");
15         out.flush();
16         out.close();
17 }