zoukankan      html  css  js  c++  java
  • 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对象,将数据输出到了客户端。

    二、response对响应的设置

    1、response对象设置响应行状态码:

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setStatus(404);
        }

     2、response对象添加响应头:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Date date=new Date(121344444);
    response.addHeader("zzz","I love JAVA.");
    response.addIntHeader("myself",22);
    response.addDateHeader("Time:",date.getTime());
    }

     3、response对象设置响应头:

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date date=new Date(121344444);
        response.addHeader("zzz","I love JAVA.");
        response.addIntHeader("myself",22);
        response.addDateHeader("Time:",date.getTime());
        response.setIntHeader("myself",23);
        }

  • 相关阅读:
    智能指针和二叉树(2):资源的自动管理
    c++智能指针和二叉树(1): 图解层序遍历和逐层打印二叉树
    QLineEdit拾遗:数据的过滤、验证和补全
    为Qt视图中的文字添加彩虹渐变效果
    python3的变量作用域规则和nonlocal关键字
    三种方法为QLineEdit添加清除内容按钮
    配置CLion作为Qt5开发环境
    c++随机排序容器中的元素
    c++性能测试工具:google benchmark入门(一)
    shared_ptr和动态数组
  • 原文地址:https://www.cnblogs.com/zhai1997/p/11484889.html
Copyright © 2011-2022 走看看