Response_输出字符数据以及输出字节数据
步骤:
1.获取字符输出流
2.输出数据
@WebServlet(name = "ResponseDemo3", value = "/ResponseDemo3") public class ResponseDemo3 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取字符输出流 PrintWriter writer = response.getWriter(); //2.输出数据 writer.println("你好啊啊啊 response"); } }
注意:
乱码问题:
1.编解码不一致:PrintWriter writer = response.getWriter();:获取的流的默认编码是ISO-8859-1
2.设置该流的默认编码
3.告诉浏览器响应体使用的编码
@WebServlet(name = "ResponseDemo3", value = "/ResponseDemo3") public class ResponseDemo3 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取流对象之前,设置流的默认编码:IOS-8859-1 设置为:GBK // response.setCharacterEncoding("GBK"); //告诉浏览器,服务器发送的消息体数据的编码,建议浏览器使用编码解码 // response.setHeader("content-type", "text/html;charset=utf-8"); //简单的形式,设置编码 response.setContentType("text/html;charset=utf-8"); //1.获取字符输出流 PrintWriter writer = response.getWriter(); //2.输出数据 writer.println("你好啊啊啊 response"); } }
输出字节数据
步骤:
1.获取字节输出流
2.输出数据
@WebServlet(name = "ResponseDemo4", value = "/ResponseDemo4") public class ResponseDemo4 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //1.获取字节输出流 ServletOutputStream sos = response.getOutputStream(); //2.输出数据 sos.write("你好".getBytes("utf-8"));//转换字节 } }
标签:输出,字节,ResponseDemo3,request,HttpServletResponse,Response,response From: https://www.cnblogs.com/qihaokuan/p/16964245.html