其他分享
首页 > 其他分享> > 案例-服务器输出字符数据到浏览器和服务器输出字节数据到浏览器

案例-服务器输出字符数据到浏览器和服务器输出字节数据到浏览器

作者:互联网

案例-服务器输出字符数据到浏览器

步骤:

  1. 获取字符输出流
  2. 输出数据

注意:

java代码

package com.bai.Servlet01;


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("/ResponseDemo03")
public class ResponseDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取流对象之前 设置流的默认编码:ISO-8859-1 设置为utf-8
        resp.setCharacterEncoding("utf-8");

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

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

        // 
        PrintWriter pw = resp.getWriter();
        //输出数据
        pw.write("<h1>Hello response</h1>");
        //输出数据
        pw.write("Hello response");
        pw.write("\n");
        //输出数据
        pw.write("你好 response");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

运行结果

 

 

 服务器输出字节数据到浏览器

  1. 获取字节输出流
  2. 输出数据

 java代码

package com.bai.Servlet01;


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("/ResponseDemo04")
public class ResponseDemo04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        //获取字节输出流
        ServletOutputStream sos = resp.getOutputStream();
        //输出数据
        sos.write("你好".getBytes("utf-8"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

标签:输出,浏览器,resp,import,服务器,servlet,javax
来源: https://www.cnblogs.com/aimz01/p/16575861.html