Java 无法在 JSP 中设置标头。响应已经提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2030152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot set header in JSP. Response already committed
提问by Susmitha Pandi
WebSphere logs the warning message “SRTServletRes W WARNING: Cannot set header. Response already committed” for one JSP request. I need the respone headers later in my code. I did some research and understood that Servlet is trying to send more data to the output stream, but the stream is already been committed. I did not understand why this is happening to only this particular JSP, as this Servlet code works fine for other JSPs. This page is not redirected and I get the response back with no response headers.
WebSphere 记录警告消息“SRTServletRes W 警告:无法设置标头。对于一个 JSP 请求,响应已经提交”。我稍后需要在我的代码中使用响应标头。我做了一些研究,了解到 Servlet 正在尝试向输出流发送更多数据,但该流已经被提交。我不明白为什么这只会发生在这个特定的 JSP 上,因为这个 Servlet 代码适用于其他 JSP。此页面未重定向,我返回的响应没有响应标头。
采纳答案by BalusC
When a response is committed, it means that at least the headers are already been sent to the client side. You cannot set/change headers when the response is already committed, because it's too late.
当响应被提交时,这意味着至少标头已经发送到客户端。当响应已经提交时,您无法设置/更改标头,因为为时已晚。
A response will be committed whenever one or more of the following conditions is met:
只要满足以下一项或多项条件,就会提交响应:
HttpServletResponse#sendRedirect()
has been called.- More than 2K has already been written to the response output, either by Servlet or JSP.
- More than 0K but less than 2K has been written and
flush()
was been invoked on the response output stream, either by Servlet or JSP.
HttpServletResponse#sendRedirect()
已被调用。- 超过 2K 的数据已经被 Servlet 或 JSP 写入响应输出。
- 超过 0K 但小于 2K 已写入并
flush()
在响应输出流上被 Servlet 或 JSP 调用。
The 2K buffer limit is configureable in appserver's configuration.
2K 缓冲区限制可在 appserver 的配置中进行配置。
You need to rearrange the code logic so that it only sets the headers beforethe response is committed. You should neverset/change the response headers using scriptletsinside/halfway a JSP. You should only do that in a Filter
before continuing the chain, or in a page controller Servlet
before dispatching the request. Also take care that neither of them are been called by a JSP include file.
您需要重新排列代码逻辑,使其仅在提交响应之前设置标头。您永远不应该在 JSP 内部/中间使用scriptlet设置/更改响应头。您应该只Filter
在继续链之前在 a 中执行此操作,或者在Servlet
分派请求之前在页面控制器中执行此操作。还要注意它们都没有被 JSP 包含文件调用。