简体   繁体   中英

Java HttpServletResponse issue width Content-Length when changing another header

: changing "Content-type" header in HttpServletResponse to "image/svg+xml" gives me an empty response, with "Content-length" showing "0" in my browser. :将HttpServletResponse中的“ Content-type”标头更改为“ image / svg + xml”会给我一个空响应,在我的浏览器中“ Content-length”显示为“ 0”。

Full description:

I'm working with a CMS plugin (in Java) that use HttpServletRequest and HttpServletResponse. There is an issue with the CMS returning "application/octet-stream" on requests to .svg files.

The plugin I'm working on is a Servlet that intercepts all request-response pairs (matching a specific URL pattern to image folders). I then check if the request string contains ".svg" and then change the Content-Type to "image/svg+xml" in the response (from "application/octet-stream").

But when I change the content type; the Content-length header is 0, and the browser displays nothing. I lose the content after changing a header in other words.

Is there some way where I can change only one header without having to write back the image content to the response? (ServletOutputStream).

I came up with one solution; which performs an extra HttpGet request (in the plugin) to the relevant svg image, before writing it into the response from an InputStream, but I think it's way too costly for each svg request on a trafficked server.

If I could only get away with changing the header, without performing extra I/O operations.

If your plugin was a Filter instead of a Servlet (maybe your framework allows filter plugins?) then you could wrap the response object in a HttpServletResponseWraper before passing the processing along, and the wrapper could save the contents to some stream in memory instead of writing it to the response stream. And then, when processing is over, you would set the header, get content that was written to memory and commit it to the response.

On a second thought: you even don't have to define this filter on the framework level. If you have access to and can freely modify the web.xml of you application, then you can easily pull it off with a plain old Java EE filter.

Anyway, I don't see why setting a content-type would reset the content. The documentation of ServletResponse.setContentType does not say anything about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM