HTTP - Response

基本概念

响应消息: 服务器端发送给客户端的数据

数据格式

1. 响应行
	1. 组成: 协议/版本	响应状态码	状态码描述
				HTTP/1.1		200				OK
	2. 响应状态码: 服务器告诉客户端浏览器本次请求和响应的一个状态
		1. 状态码都是3位数字
		2. 分类
			1. 1xx: 服务器接收客户端学习, 但没有接收完成, 等待一段时间后, 发送1xx状态码
			2. 2xx: 成功 
				代表: 200
			3. 3xx: 重定向
				代表: 302
			4. 4xx
				代表: 404(请求路径没有对应的资源)
						405(请求方式没有对应的方法(doPost(), doGet()))
			5. 5xx
				代表: 500, 服务器内部异常
2. 响应头
	1. 格式
		头名称: 值
	2. 常见响应头
		1. Content-Type: 服务器告诉客户端本次相应提数据格式以及编码格式
		2. Content-disposition: 服务器告诉客户端以什么格式打开相应体数据
		 	值: 
		 		in-line: 默认值, 在当前页面内打开
		 		attachment: 以附件形式打开响应体, 文件下载时使用
3. 响应空行
	一个空行, 分隔响应头和响应体
4. 响应体
	传输的数据
5. 响应字符串格式 
HTTP/2 200 OK
server: JSP3/2.0.14
date: Tue, 23 Jun 2020 12:52:13 GMT
content-type: application/javascript
content-encoding: gzip
etag: "4e097-5a8b7ef21bb00"
last-modified: Tue, 23 Jun 2020 03:27:08 GMT
expires: Fri, 21 Jun 2030 04:44:30 GMT
age: 29263
accept-ranges: bytes
cache-control: max-age=315360000
vary: Accept-Encoding,User-Agent
ohc-cache-hit: jhcm76 [4]
ohc-response-time: 1 0 0 0 0 0
X-Firefox-Spdy: h2

Response对象

功能

设置响应消息

1. 设置响应行
	1. 格式: HTTP/1.1	200	OK
	2. 设置状态码: setStatus(int sc)
2. 设置响应头
	setHeader(String name, String value)
3. 设置响应体
	使用步骤
	1. 获取输出流
		字符输出流: PrintWriter getWriter()
		字节输出流: ServletOutputStream getOutputStream()
	2. 使用输出流, 将数据输出到客户端浏览器

案例

1. 完成重定向

重定向: 资源跳转的方式
1. 告诉浏览器重定向, 状态码302
2. 告诉浏览器B资源的路径, 响应头location: B资源的路径
public class ResponseDemo01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo01......");
        //访问/responseDemo01, 会自动调转到/responseDemo02
        //1. 设置状态码为302
        resp.setStatus(302);
        //2. 设置响应头location
        resp.setHeader("location", "/response/responseDemo02");
		
		//简单的重定向方法
        resp.sendRedirect("/response/responseDemo02");
        //设置属性
        //request.setAttribute("name", "hello");
        //转发
        //request.getRequestDispatcher("/response/responseDemo02").forward(request, response);
        
    }
}
重定向和转发的区别(forward 和 redirect):
	重定向的特点: 
	1. 地址栏发生变化
	2. 重定向可以访问其他站点(服务器)的资源
	3. 重定向是两次请求, 不能使用request对象共享数据
转发的特点: 
	1. 转发地址栏路径不变
	2. 转发只能访问当前服务器下的资源
	3. 转发是一次请求, 可以使用request对象共享数据
路径的写法
1. 路径的分类
1. 相对路径, 通过相对路径不可以确定唯一资源
	如
	./index.html
	不以 / 开头, 以 . 开头
	规则: 找到访问当前资源和目标资源之间的相对位置关系
	./ : 当前资源所在的目录, 可以省略
	../ : 当前资源后退一级的目录 
2. 绝对路径, 通过绝对路径可以确定唯一资源
	如
	http://localhost/response/responseDemo02
	/response/responseDemo02
	以 / 开头路径为绝对路径
如何判断绝对路径是否要加虚拟目录
	* 规则: 判断定义的路径是给谁用的(判断请求将来从哪发出)
		* 给客户端浏览器使用: 需要加虚拟目录(项目的访问路径)
			点击超链接
			资源重定向
		* 给服务器使用: 不需要加虚拟目录
			资源跳转
动态获取虚拟目录

String request.getContextPath();

2. 服务器输出字符数据到浏览器

  1. 步骤
    • 获取字符输出流
    • 输出数据
  2. 注意乱码问题
    • PrintWriter writer = resp.getWriter()获取的流的默认编码是ISO-8859-1
    • 设置该流的编码
    • 告诉浏览器响应体使用的编码

实例:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取流对象之前, 设置流的默认编码 ISO-8859-1 -> GBK
//        resp.setCharacterEncoding("GBK");
        //2. 告诉浏览器, 服务器发送的消息体数据的编码, 建议浏览器使用该编码解码
        //下面这行代码同时会设置输出流的编码形式为utf-8, 所以不需要再写第一行代码
//        resp.setHeader("content-type", "text/html;charsert=utf-8");
        
        //简单的形式, 设置编码
        resp.setContentType("text/html;charset=utf-8");
        
        
//        1. 获取字符输出流
        PrintWriter writer = resp.getWriter();
        //2. 输出数据
        writer.write("<h1>hello response<h1>");
        writer.write("<h1>你好<h1>");
        //输出流不需要刷新, 会自动刷新
    }
  1. 服务器输出字节数据到浏览器
    • 步骤
      • 获取字符输出流
      • 输出数据
        实例:
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        resp.setContentType("text/html;charset=utf-8");
        //1. 获取字节输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //2. 输出数据
        outputStream.write("你好".getBytes("utf-8"));
    }

验证码实例

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        
        //1. 创建对象, 在内存中存图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2. 美化图片
        //2.1 填充背景色
        Graphics graphics = image.getGraphics();//画笔对象
        graphics.setColor(Color.PINK);//设置颜色
        graphics.fillRect(0, 0, width, height);//填充矩形
        //2.2 画边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0, 0, width-1, height-1);//画矩形边框
        //写验证码
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        str += str.toLowerCase();
        str += "0123456789";
        //生成随机角标
        Random random = new Random();
        
        
        for (int i = 1; i <=5 ; i++) {
            //获取字符
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            graphics.setColor(Color.BLUE);
            graphics.drawString(ch+"", width/5*i, height/2);
        }
        
        //2.4 画干扰线
        graphics.setColor(Color.GREEN);
        for (int i = 0; i < 10; i++) {
            
            
            //随机生成坐标点
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            //画线
            graphics.drawLine(x1,x2,y1,y2);
        }
        
        //3. 将图片输出展示
        ImageIO.write(image, "jpg", resp.getOutputStream());
  
        resp.setContentType("text/html;utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("nihao图片");
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值