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);
        }
    }

    结果:

    迎风少年
  • 相关阅读:
    总结ORACLE学习8023
    set @CurrentID=@@IDENTITY
    一个IT人:跳槽一定要谨慎
    SQL Server数据库开发(转自CSDN)
    46个不得不知的生活小常识
    CodeProjectSome Cool Tips For .Net 之一
    数据库原理综合习题答案
    EDM
    CodeProject Some Cool Tips for .NET之二
    The operation is not valid for the state of the transaction.
  • 原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13668947.html
Copyright © 2011-2022 走看看