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

    结果:

    迎风少年
  • 相关阅读:
    noip欢乐赛10.24 分火腿
    noip2014 无线网络发射器选址/wireless.
    noip2012 借教室 线段树最小值做法
    Codevs1021题解---SPFA+路径记录
    Vijos1448题解---线段树+括号法
    Vijos1425题解---栈
    Codevs1022题解---匈牙利算法
    人们总要为曾经的年轻买单
    2017-10-26
    2017-10-24LCA
  • 原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13668947.html
Copyright © 2020-2023  润新知