servlet中response中文乱码

  在servlet中,通过response向浏览器写中文,会出现乱码,那么response向浏览器写数据一共有两种方式

    1.getOutputStream.write();字节流

    2.PrintWriter.write();字符流

  我们都知道,字节流可以读写任何的数据,而字符流只能读写字符数据。

  这里是怎么把我们servlet的数据写到浏览器的,要说一下,这里是我们把数据先写进response里面,然后服务器看到response里面有数据,那么这时服务器才写给浏览器,才会显示我们要写入的数据。简单的画张图。

  首先说第一种写入getOutputStream.write();字节流,通过这个流来写中文,是没有问题的,代码

1         String data = "中国";
2         
3         OutputStream out = response.getOutputStream();
4         out.write(data.getBytes());

  上面这样做是没有问题的,注意,但是我们要实现国际化,这里我们就不能不修改,我们正常用的是UTF-8,那我们就改成utf-8,注意我们是在data转成字节时改,

1         String data = "中国";
2         
3         OutputStream out = response.getOutputStream();
4         out.write(data.getBytes("utf-8"));

  这样一改就肯定会乱码,我们在这里转成字节的时候用的utf-8的码表,而浏览器默认的是什么啊,是gb2312,这肯定乱码嘛,你用utf-8码表去对应gb2312,肯定会出问题,怎么修改

我们通过设置响应头,来规定浏览器你就按这个码表去查,就没问题,设置响应头,设置content-type

1         response.setHeader("content-type", "text/html;charset=utf-8");
2         String data = "中国";
3         
4         OutputStream out = response.getOutputStream();
5         out.write(data.getBytes("utf-8"));

  这样一来的话浏览器就会按照utf-8去差,就不会出现乱码的问题,修改这个问题还有一个方法,我们在学习html的时候,这个meta标签可以模拟代替一个响应头,我们通过设置这个meta也可以做到

1         String data = "中国";
2         
3         OutputStream out = response.getOutputStream();
4         out.write("<meta http-equiv='content-type' content='text/html;charset=utf-8'>".getBytes());
5         out.write(data.getBytes("utf-8"));

  这样做也是可以的,运行,我们可以看一下这个网页的源码

  下面说一下PrintWriter.write();字符流

1         String data = "中国";
2         
3         PrintWriter print = response.getWriter();
4         print.write(data);

  这样写的话浏览器会给我显示两个问号,问什么是两个问号呢?,因为这个字符流底层用的iso-8859-1的码表,老外写的嘛,老外就喜欢用这个,那我们应该这样转码

1         String data = "中国";
2         response.setCharacterEncoding("utf-8");
3         response.setHeader("content-type", "text/html;charset=utf-8");
4         PrintWriter print = response.getWriter();
5         print.write(data);

  response.setCharacterEncoding("utf-8");设置response用什么码表,达到控制response以什么码表像浏览器写数据的目的

  response.setHeader("content-type", "text/html;charset=utf-8");用这个来设置浏览器用什么码表对应我们的数据。

  这样一来我们的文字有变成我们想要的文字了,但是设置API的人知道这两句话是常用的,经常写的,防止代码的冗余,我们可以这样写,就代替了这两句话,但是我们要明白里面是怎么做的。

 

1         String data = "中国";
2         response.setContentType("text/html;charset=utf-8");
3         PrintWriter print = response.getWriter();
4         print.write(data);

 

response.setContentType("text/html;charset=utf-8");这一段代码就做了上面两句代码的事情,如果你去查看源码的话,你就明白了。

 

 

posted @ 2013-12-25 11:47  哎呦喂,我的小祖宗╰つ  阅读(507)  评论(0编辑  收藏  举报