学过Java SE的应该清楚Java中得IO流有以下几个:
字符流:Writer 和 Reader; 字节流:OutputStream 和 InputStream
当然Servlet向浏览器输出数据也就有两种方式了。
字节流方式:
OutputStream out = response.getOutputStream();
out.write("Hello, world!".getBytes());
字符流方式:
PrintWriter out = response.getWriter();
out.println("Hello, world!");
引起乱码的原因主要是:浏览器的解码和数据的编码不一致。由于 jar 包得源代码是外国人写的,默认编码一般是 ISO-9881. 并且这种编码方式没有中文的编码,中文在编码为问号的编码。因此,只要 response 的编码格式和浏览器的解析格式相同,则不会产生乱码。两种方式的解决编码问题的方法:
字节流方式的解决方法:
OutputStream out = response.getOutputStream();
out.write("Hello, world!".getBytes("utf-8")); //在这里指定编码成字节码的编码方式
response.setContentType("text/html;utf-8");
字符流的解决方式:
response.setCharacterEncoding("utf-8"); //在这里设置编码方式
PrintWriter out = response.getWriter();
out.println("Hello, world!");
response.setContentType("text/html;utf-8");