response向客户端写入数据

1、写入文字:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");//设置服务器的编码,默认是ISO-8859-1
        response.setContentType("text/html; charset = utf-8");//告诉浏览器服务器的编码格式
        response.getWriter().write("你好,JAVA");
    }

 2、图片:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream out=response.getOutputStream();
        File file=new File("图片路径");
        FileInputStream fi = new FileInputStream(file);
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fi.read(buf)) != -1) {
            out.write(buf, 0, len); // 将数组中的指定长度的数据写入到输出流中。
        }
        fi.close();
        out.close();
    }

采用了缓冲数组读入图片数据,减少了时间的消耗。创建ServletOutputStream对象,将数据输出到了客户端。

猜你喜欢

转载自www.cnblogs.com/zhai1997/p/11484889.html