0

I have configured CloudFront in front of my web application that uses JSP pages, but it will not cache my page because the Content-Length header is not set.

Is there a way that I can get JSP to include the Content-Length, or do I need to do something ugly like have a filter than streams the content to determine it's length, then streams it to the response stream afterwards (setting the ContentLength header first).

RobbiewOnline
  • 1,350
  • 1
  • 16
  • 36
  • According to the documentation, lacking a `Content-Length` header [does not prevent](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#ResponseCustomDroppedTCPConnections) CloudFront from caching response content. I suspect that should probably be asking about CloudFront not caching your content (problem) rather than about how to handle missing Content-Length (attempted solution) -- see also [The XY Problem](http://xyproblem.info). Can you provide an example URL that exhibits the behavior? – Michael - sqlbot Jan 09 '19 at 15:15
  • I can confirm that setting a content length did resolve the issue. Any JSP page exhibited this issue until I added the length. – RobbiewOnline Mar 04 '19 at 10:39

2 Answers2

0

You can set Content-Length using JSP's HttpServletResponse

The response object is an instance of a javax.servlet.http.HttpServletResponse object.

We can use the following methods to set HTTP response header in your servlet program.

Call setContentLength method

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Thanks - but doesn't JSP already know the length of the content it's outputting to the response, so doesn't it try to set the Content-Length header itself? If not, when / where can I do it. My initial thoughts are a filter, but this sounds like I'd have to stream the original response somewhere first because I can't write a response header before I know the length of the content (e.g temporarily in-memory/disk) then capture it's length before streaming back through the response? If not a filter then within the JSP I wouldn't know the length in advance. – RobbiewOnline Jan 09 '19 at 11:52
  • @DevologyLtd maybe you missing `Content-Length` ? https://stackoverflow.com/questions/35590622/cloudfront-with-s3-website-as-origin-is-not-serving-gzipped-files – Ori Marko Jan 09 '19 at 12:16
  • Thanks @user7294900 - but that XML AllowedHeader is for CORS Configuration with S3 buckets and I'm using vanilla JSP. – RobbiewOnline Jan 09 '19 at 13:05
0

I have found a way to do this by using a filter which works well for my needs, I even process the JSP first to remove whitespaces then chain the result of that into the ContentLengthFilter.

RobbiewOnline
  • 1,350
  • 1
  • 16
  • 36