代码
步骤 获取字符输出流PrintWriter writer = resp.getWriter(); 输出数据writer.write("你好,中国!");writer.write("hello China!");
@WebServlet("/responseDemo3")
public class ResponseDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取字符输出流
PrintWriter writer = resp.getWriter();
//输出数据
writer.write("你好,中国!");
writer.write("hello China!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
访问http://localhost:8080/day15/responseDemo3的结果,出现了中文乱码
??????!hello China!
中文乱码原因 服务器的编码格式(即Tomcat的编码格式)为ISO-8859-1,无法解析中文 浏览器的编码格式为GBK,与服务器的编码格式不同
解决办法
1. 获取流对象之前,设置流的编码,由默认编码ISO-8859-1设置为GBK
resp.setCharacterEncoding("GBK");
结果:虽然解决了中文乱码的上诉两个问题,但是如果浏览器的编码格式为utf-8,则不能解决第二条问题
假如浏览器的编码格式为utf-8,依然如上设置,就会出现如下结果
浣犲ソ锛屼腑鍥!hello China!
2.告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码解码
resp.setHeader("content-type","text/html;charset=utf-8");
此方法就是设置响应头content-type的值为text/html;charset=utf-8
3.更简便的方法(重点)
直接设置响应头content-type的值为text/html;charset=utf-8
resp.setContentType("text/html;charset=utf-8");
最终代码
@WebServlet("/responseDemo3")
public class ResponseDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取流对象之前,设置流的编码,由默认编码ISO-8859-1设置为GBK
//resp.setCharacterEncoding("utf-8");
//告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码解码
//resp.setHeader("content-type","text/html;charset=utf-8");
//简单的方式设置编码
resp.setContentType("text/html;charset=utf-8");
//获取字符输出流
PrintWriter writer = resp.getWriter();
//输出数据
writer.write("你好,中国!");
writer.write("hello China!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}