• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when to use setContentLength()

 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have seen this pattern in several places, but this snippet is from Sun's j2ee tutorial.

My question is: When we need to use setContentLength()?

I would think that the OuputStream provided by the servlet container would always increment the Content-Length header field when adding bytes to the response, but it appears not.


 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would think that the OuputStream provided by the servlet container would always increment the Content-Length header field when adding bytes to the response, but it appears not.

Now how in the world could it do that? The headers are sent when the first output buffer is full (or flushed.) Typically before the response has been completely generated.
In my experience, some plug-ins - such as PDF viewers - do not work correctly if the content-length is not supplied.
Bill
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The headers are sent when the first output buffer is full (or flushed.) Typically before the response has been completely generated.


That explains why the Content-Length header field is not set by the servlet container.

However, I notice that most code examples do not set the Content-Length header field while a few do. How do I know when this is necessary?
 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't worry about setting this field. If chunked encoding used, then content length shouldn't be set, in this case you can also set some headers in the end of stream. Some servlet containers are capable buffer your servlet out, so tey set content length when you close stream.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't worry about setting this field. If chunked encoding used, then content length shouldn't be set, in this case you can also set some headers in the end of stream. Some servlet containers are capable buffer your servlet out, so tey set content length when you close stream.

1. setting headers in the "end of stream"
2. servlet containers that buffer servlet out and "set content length"
Care to give us an API for #1 and an example of #2
My practice is to set content length for all images and other resources when the length is easily found - such as image files.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic