简体   繁体   English

需要根据Servlet响应有条件地设置HTTP标头

[英]Need to Set HTTP Headers Conditionally on Servlet Response

I want to set HTTP headers depending on the type of response. 我想根据响应的类型设置HTTP标头。 My problem is that some reponses commit their headers before I can set mine. 我的问题是,某些回复在我可以设置我的回复之前就提交了标头。 Any suggestions about how to handle this? 有关如何处理此问题的任何建议?

One idea is to set the response header in the response object in a filter before the servlet is called. 一种想法是在调用Servlet 之前在过滤器的响应对象中设置响应头。

Another one is to provide the servlet with a response wrapper that prevents the real response from actually being committed. 另一个是为Servlet提供响应包装器,以防止实际提交实际响应。 This might entail buffering the response body in memory. 这可能需要在内存中缓冲响应主体。

But I think that the best approach is to modify the servlets so that they set the required headers. 但是我认为最好的方法是修改servlet,以便它们设置所需的标头。


Do I HAVE to buffer the entire response by providing my own outputstream to the wrapper ? 我是否需要通过向包装器提供自己的输出流来缓冲整个响应? Can I overwrite flush() or something like that ? 我可以覆盖flush()或类似的东西吗?

It is up to you how you implement it. 如何实现它取决于您。 The constraint is that response wrapper object must somehow arrange that the special header gets added before the writing of the response body starts. 约束条件是响应包装对象必须以某种方式安排在开始编写响应主体之前添加特殊标头。 The conceptually simple way is to buffer the response body, but you could also get the response wrapper to provide an output stream / writer that adds the header before the first flush to the real response output stream / writer. 从概念上讲,简单的方法是缓冲响应主体,但是您也可以使响应包装器提供一个输出流/编写器,该输出流/编写器将第一次刷新之前的标头添加到实际响应输出流/编写器中。

I am worried about buffering causing performance issues 我担心缓冲会导致性能问题

Yes, well it could do, though you would need to look at the entire webapp to determine if this is significant. 是的,它可以做到,尽管您需要查看整个Web应用程序以确定这是否有意义。

From a performance perspective, the best solution is to get the servlet to set the header itself. 从性能角度来看,最好的解决方案是让servlet设置标头本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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