需要注意的是OutputStream和write的冲突问题
1、使用OutputStream输出中文数据
package cn.itcast.response;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//用outputStream输出中文数据的问题
public class ResponseDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test4(response);
}
//写数字给浏览器的问题
public void test4(HttpServletResponse response) throws IOException{
response.getOutputStream().write((120+"").getBytes("UTF-8"));
}
//用<meta> 模似一个http响应头,控制浏览器以UTF-8打开数据
public void test3(HttpServletResponse response) throws IOException{
response.getOutputStream().write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
String data = "中国";
OutputStream out = response.getOutputStream();
out.write(data.getBytes("UTF-8"));
}
//输出UTF-8的数据,有问题,需要控制浏览器以utf-8打开
public void test2(HttpServletResponse response) throws IOException{
//<meta> 模似一个http响应头
//使用http协议控制浏览器以utf-8打开下面发送的数据
response.setHeader("content-type", "text/html;charset=UTF-8");
String data = "中国";
OutputStream out = response.getOutputStream();
out.write(data.getBytes("UTF-8"));
}
//输出gb2312的数据,没有问题
public void test1(HttpServletResponse response) throws IOException{
String data = "中国";
OutputStream out = response.getOutputStream();
out.write(data.getBytes());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2、使用writer输出中文数据
package cn.itcast.response;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//用Writer输出中文数据
public class ResponseDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test1(response);
}
public void test2(HttpServletResponse response) throws IOException{
//这句话调用后,相当于把response.setCharacterEncoding("UTF-8"); 也设好了
response.setContentType("text/html;charset=UTF-8");
String data = "中国";
PrintWriter writer = response.getWriter();
writer.write(data);
}
public void test1(HttpServletResponse response) throws IOException{
//更改response的码表,通知服务器用UTF-8码表去取response中的数据,然后写给客户机
response.setCharacterEncoding("UTF-8");
//通知浏览器以UTF-8码表打开回送的数据
//response.setHeader("content-type", "text/html;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
String data = "中国";
PrintWriter writer = response.getWriter();
writer.write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}