This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Servlets and the fly likes setContentLength Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "setContentLength" Watch "setContentLength" New topic
Author

setContentLength

Paul Medford
Ranch Hand

Joined: Aug 28, 2001
Posts: 33
I'm puzzled with this one. The API says that the ServletResponse.setContentLength(int len) method sets the HTTP Content-Length header.
How can the Servlet container or Servler programmer know in advance how long the content will be and set it first in the header before the content is even produced?
Any idea?
Francois
Manjunath Reddy
Ranch Hand

Joined: Jul 26, 2001
Posts: 60
No comments with respect to HTTP response...but i have used this to write ms-word or pdf files to the client.
jasonkosowan
Greenhorn

Joined: Sep 07, 2001
Posts: 25
Usually, before even the header is given back to the browser, servlets buffer the response, so you can set the content length on the fly.
As far as figuring out the length of content, you usually don't have to unless it's an unusual format (dynamically-created gif, pdf, serialized object, etc). In this case, just set the content-length equal to the byte-length of the file or object that you want to send back.
Originally posted by Francois Merle:
I'm puzzled with this one. The API says that the ServletResponse.setContentLength(int len) method sets the HTTP Content-Length header.
How can the Servlet container or Servler programmer know in advance how long the content will be and set it first in the header before the content is even produced?
Any idea?
Francois

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 15964
    
  19

You have to compute it. The content-length isn't mandatory in most cases, but there's one infamous exception - if you write a PDF, Netscape will choke on it if there's no content-length. I had to write the PDF to a temp file, get the length of the temp file, set the content-length header, then spool the temp file out to the client to make this work.

Customer surveys are for companies who didn't pay proper attention to begin with.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: setContentLength
 
Similar Threads
code for file download
Servlet is being dowloaded
renaming pdf file via servlet
download text file (CSV) from database to browser through servlet
content type