//用response的outputStream输出中文
public class ResponseDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test4(response);
}
//方法二,用meta标签模似一个http响应头,控制浏览器以u8打开
private void test2(HttpServletResponse response)
throws UnsupportedEncodingException, IOException {
String data = "中国";
byte b[] = data.getBytes("UTF-8");
response.getOutputStream().write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
response.getOutputStream().write(b);
}
//方法一
private void test1(HttpServletResponse response)
throws UnsupportedEncodingException, IOException {
//设置一个头信息,通知浏览器以U8打开
response.setHeader("content-type", "text/html;charset=UTF-8");
String data = "中国";
byte b[] = data.getBytes("UTF-8");
response.getOutputStream().write(b);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
二,用response的write写数据:
//response的write流输出中文的问题
public class ResponseDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//用write流写字符,它会默认查询ISO8859-1的码表
//这句话是让它去查u8的码表
response.setCharacterEncoding("UTF-8");
//在通知浏览器以u8打开
response.setHeader("content-type", "text/html;charset=UTF-8");
//写了这句话就相当于上面两句话
// response.setContentType("text/html;charset=UTF-8");
String data = "中国";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}