Question

When the setContentLength method is used to set the length of the response with a higher size that is higher than the actual size, why is the container not auto calculating the length?

for instance,

String s = "hello";
byte[] b = s.getBytes();

response.setContentLength(100);
response.getOutputStream().write(b);
response.flush();

When i hit the servlet, it takes about half a minute to load the page, is this because of the content length header..?

What is the need for such a method? why cant the container be made to calculate the length of the response by itself?

Was it helpful?

Solution

If you want to return large contents it is often not practical to load te full response and send it at once,but instead load and send it in chunks. Since the length is sent as part of the beginning of the response there is no way for the container to later on change it.

In this case you tell the container that your response is 100 bytes, you send the first 5 bytes (which triggers the header "Content-Length: 100" to also be sent), so now the recipient will expect another 95 bytes.

Now, on the other hand, say your content was 10GB, you would not want to first load all of that into memory just so the container would calculate the size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top