Response_案例_输出数据_hehe.employment.over.15.4

文章目录

  • 15.6 Response_案例_服务器输出字符数据到浏览器
  • 15.7 Response_案例_服务器输出字节数据到浏览器

15.6 Response_案例_服务器输出字符数据到浏览器

  • 步骤:
    • 1.获取字符输出流
    • 2.输出数据
  • note:
    • 乱码问题:
      • 1.PrintWriter pw = response.getWriter();获取的流的默认编码是ISO-8859-1
      • 2.设置该流的默认编码
      • 3.告诉浏览器响应体使用的编码
        • response.setContentType("text/html;charset=utf-8");//简单的形式,设置编码,是在获取流之前设置
  • 示例:
package com.xww.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 重定向
 */
@WebServlet( "/responseDemo3")
public class ResponseDemo3 extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        //1.获取流对象之前,设置流的默认编码:ISO-8859-1 设置为:GBK
        // response.setCharacterEncoding("utf-8");

        //2.告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码解码
        //response.setHeader("content-type","text/html;charset=utf-8");

        //简单的形式,设置编码
        response.setContentType("text/html;charset=utf-8");

        //1.获取字符输出流
        PrintWriter pw = response.getWriter();
        //2.输出数据
        pw.write("除了文本,还可以是HTML标签");
        pw.write("

标题

"
); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }

15.7 Response_案例_服务器输出字节数据到浏览器

  • 步骤:
    • 1.获取字节输出流
    • 2.输出数据
  • 示例:
package com.xww.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 重定向
 */
@WebServlet( "/responseDemo4")
public class ResponseDemo4 extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        //1.获取流对象之前,设置流的默认编码:ISO-8859-1 设置为:GBK
        // response.setCharacterEncoding("utf-8");

        //2.告诉浏览器,服务器发送的消息体数据的编码。建议浏览器使用该编码解码
        //response.setHeader("content-type","text/html;charset=utf-8");

        //简单的形式,设置编码
        response.setContentType("text/html;charset=utf-8");

        //1.获取字节输出流
        ServletOutputStream sos = response.getOutputStream();
        //2.输出数据
        sos.write("字节输出流一般用于输出图片".getBytes("utf-8"));//记得规定编码格式
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        this.doPost(request,response);
    }
}

你可能感兴趣的:(#,间接,over,java,servlet)