是否可以在Java Servlet环境中交换http请求和响应?

时间:2014-11-18 20:50:42

标签: java http servlets request response

我正在开发一个服务器控件,以避免在Java服务器端重复处理相同的请求类型。 主要目标是避免用户通过重复单击硬处理请求来充斥我的服务器处理器。 我正在开发一个Servlet过滤器来控制请求流,但是如果有一个仍在处理的先前请求,我可以通过返回HTTP 204状态来“中止”第二个请求。 从服务器的角度来看,没关系。但是,Web浏览器只处理“中止”请求,而不是第一个请求。

Browser sends request "A"
Server starts to process the request "A"
Browser sends request "B"
Server aborts request "B" (HTTP 204)
Browser receives response "B" (Aborted)
Server finishes the request "A"
Browser does not displays / receives the request "A"

所以,最后问题。 是否可以更改请求的响应? 因此,我可以避免服务器端的重复处理,浏览器可以显示请求的内容。

您能否提出另一种方法来解决这个问题?

Browser sends request "A"
Server start processing request "A"
Browser sends request "B"
Server "holds" request "B"
Server finishes the request "A"
Server forwards the request "B" to the the response "A"
Server aborts the request "A" (http 204)
Browser displays / receives the request "B" with the response "A" content / headers

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以使用micro-caching而不是使用此方法,即缓存内容的持续时间很短,例如1s,10s。这种方式而不是http204,您返回缓存的内容。您的用户会对此方法感到满意。您可以synchronize您的servlet代码,这样您的servlet中只会处理一个请求。但请注意synchronized servlet is not a good design

答案 1 :(得分:0)

我将基于@BalusC的Stack Overflow回答做一个缓存。 How to read and copy the HTTP servlet response output stream content for logging。 我无法交换其他请求的响应,但我可以在短时间内缓存先前的响应。后续请求可以接收缓存的响应,因此可以避免处理器泛滥。 感谢@eduyayo的建议。