zoukankan      html  css  js  c++  java
  • Servelet------14 response 响应对象获取字节流

    response响应对象也为我们提供了字节输出流,字节输出流可以输出任意的数据,接下来我们来进行简单的演示。

     代码:

    @WebServlet("/servlet01")
    public class Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取字节输出流
            ServletOutputStream os = response.getOutputStream();
            //写出数据
            os.write("你好".getBytes());
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }

     结果:

     可以看出我们将字符串转变成字节数组后输出浏览器,并没有产生乱码,说明浏览器和字符串的获取字符数组的编解码方式是相同的:

    我们知道浏览器的编解码格式在默认情况下适合操作系统默认相同的,在中国也就是gbk,其实字符串的获取字节数组的方法的编码格式也是和当前操作系统的编解码格式相同的。

    我们可以将字符串获得字节数组的编码格式修改成utf-8,然后进行输出,不出意外会乱码:

    @WebServlet("/servlet01")
    public class Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取字节输出流
            ServletOutputStream os = response.getOutputStream();
            //写出数据
            os.write("你好".getBytes("utf-8"));
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }

    结果:

     解决办法就是告诉浏览器该怎么解码:

    @WebServlet("/servlet01")
    public class Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            //获取字节输出流
            ServletOutputStream os = response.getOutputStream();
            //写出数据
            os.write("你好".getBytes("utf-8"));
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }

    结果:

    迎风少年
  • 相关阅读:
    003.Heartbeat MySQL双主复制
    001.常见监控简介
    微服务探索与实践—服务注册与发现
    设计模式之建造者模式
    .NET Core 3.0之深入源码理解Startup的注册及运行
    【译】.NET Core 3.0 Preview 3中关于ASP.NET Core的更新内容
    C#并发编程之异步编程(三)
    设计模式之中介者模式
    设计模式之单例模式
    设计模式之装饰器模式
  • 原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13668947.html
Copyright © 2011-2022 走看看