HttpServletResponse接口

1.HttpServletResponse接口简介

  1. 该接口来自于Servlet规范中,在Tomcat中存在servlet-api.jar
  2. 该接口实现类由Http服务器负责提供
  3. 该接口负责将doPost/doGet方法执行结果写入到【响应体】交给浏览器
  4. 习惯将该接口修饰的对象称为【响应对象】、

2.主要功能

  1. 将执行结果以二进制形式写入到【响应体】
  2. 设置响应头中【content-type】属性值,从而控制浏览器使用,对应编译器将响应体【二进制数据】编译为【文字,图片,视频,命令,,】
  3. 设置响应头中【location】属性,将一个请求地址赋值给location,从而控制浏览器向指定服务器发送请求

3.实例

抽象类的作用:降低接口实现类对接口实现过程难度
      		将接口中不需要使用抽象方法交给抽象类进行完成
            接口实现类只需要对接口需要的方法进行实现

	Tomcat根据Servlet规范调用Servlet接口实现类实例对象
      1.Tomcat有权创建Servlet接口实现类实例对象
        Servlet OneServlet = new OneServlet();
      2.Tomcat根据实例对象调用service方法处理当前请求
3.1输出流
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String str = "hello world!!";
        //---响应对象将响应结果写到响应体中

        //通过响应对象向Tomcat服务器索要输出流
        PrintWriter out = response.getWriter();
        //通过输出流,将执行结果以二进制形式写到响应体中
        out.write(str);

    }//doGet方法执行完毕
    //Tomcat将包推送给浏览器
3.2 输出文本,字符编码
/**
 * 默认情况下,content-type属性值为"text",
 * 此时浏览器将会采用【文本编辑器】对响应体二进制数据进行解析
 * 一定要在得到输出流之前,通过响应对象对响应头的content-type属性进行一次重新赋值
 * 用于指定浏览器采用正确编译器
 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String result = "java<br/>html<br/>mysql<br/>";//既有文字命令又有标签命令
        String result2 = "红烧肉";

        //设置content-type
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(result);
        out.print(result2);

    }
3.3 输出流为数字用print
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int money=40;
        PrintWriter out = response.getWriter();
        out.println(money);
        out.println(money+20);
    }
3.4 location属性跳转
/**
     * 浏览器在接收到响应包后,如果发现响应头存在location属性
     * 自动通过地址栏向location指定网站发送请求
     * sendRedirect方法远程控制浏览器请求行为【请求地址,请求方式,请求参数】
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String re = "http://www.baidu.com?userName=f";
        //通过响应对象将地址赋值给响应头中location属性
        resp.sendRedirect(re);//响应头 location="http://www.baidu.com"
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值