消息头的响应头中有字段Content-Length
- 作用是描述HTTP消息实体的传输长度
- 浏览器通过Content-Length可以得知本次传输何时结束
下面根据已知响应体长度设置不同的Content-Length来观察具体表现
一.前端代码展示:
<%--
Created by IntelliJ IDEA.
User: WHW
Date: 2019/7/23
Time: 18:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<b>已知:</b><br/>
消息体为:"ABCDEFGHIJKLMN"<br/>
bodyLength=14<br/>
<b>设置Content-Length:</b>
<fieldset>
<a href="http://localhost:8080/rr/cls?value=13">13</a>
</fieldset>
<fieldset>
<a href="http://localhost:8080/rr/cls?value=14">14</a>
</fieldset>
<fieldset>
<a href="http://localhost:8080/rr/cls?value=15">15</a>
</fieldset>
</body>
</html>
二.Servlet代码展示
package controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author weihuanwen
* @Date 2019/7/25 8:05
* @Version 1.0
*/
@WebServlet(urlPatterns = "/cls")
public class ContentLengthServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端设置的Content-Length
String valueStr = req.getParameter("value");
int contentLength = Integer.parseInt(valueStr);
//设置Content-Length
resp.setContentLength(contentLength);
//设置响应消息体
resp.getWriter().write("ABCDEFGHIJKLMN");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
三.前端网页展示

四.测试
1.Content-Length<bodyLength时:


2.Content-Length=bodyLength时:


3.Content-Length>bodyLength时:

![]()

五.总结:
当Content-Length<=bodyLength时,响应体中的数据可以正常显示
当Content-Length>bodyLength时,此时二者的差值使得客户端浏览器始终处于等待解析的状态,表现为卡顿
本文探讨了HTTP响应头中的Content-Length字段在JWeb中的作用,它用于指示消息实体的传输长度。通过设置不同Content-Length值的测试,发现当Content-Length小于等于实际body长度时,数据能正常显示;而当Content-Length大于body长度,会导致浏览器解析时出现卡顿。
464

被折叠的 条评论
为什么被折叠?



