Response输出字符数据和Response输出字节数据
Response输出字符数据
步骤:
1.获取字符输出流
2.输出数据
@WebServlet("/responseD3") public class ResponseD3 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取字符出出流 PrintWriter pw = response.getWriter(); //输出数据 //pw.write("<h1>hello Response</h1>"); pw.write("<h1>你好 Response</h1>"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
出现中文乱码
乱码原因:编解码使用的字符集不一致
1.PrintWriter pw = response.getWriter(); 获取的流的默认编码是ISO=8859-1
2.设置该流的默认编码
3.告诉浏览器响应体使用的编码
设置编码,是在获取流之前进行设置的
@WebServlet("/responseD3") public class ResponseD3 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //告诉浏览器,服务器发送的消息体数据的编码。建议使用该编码解码 //response.setHeader("content-type","text/html;charset=utf-8"); //简单形式 response.setContentType("text/html;charset=utf-8"); //获取字符出出流 PrintWriter pw = response.getWriter(); //输出数据 //pw.write("<h1>hello Response</h1>"); pw.write("<h1>你好 Response</h1>"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
推荐使用简单形式
Response输出字节数据
步骤:
1.获取字节输出流
2.输出数据
@WebServlet("/responseD4") public class ResponseD4 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //简单形式 response.setContentType("text/html;charset=utf-8"); //获取字节输出流 ServletOutputStream sos = response.getOutputStream(); //输出数据 sos.write("hello".getBytes("utf-8")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }