Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a detached HttpServletRequest and HttpServletResponse provided by the Servlet Container?

Tags:

java

servlets

I want to implement the following logic: when I receive HttpServletRequeset and HttpServletResponse in main servlet's doService method (in the main web Container thread),I start A,B,C three threads (thread managed by my own program) to process other servlet in parallel mode,and then join each response from these servlet in main thread,and if one of my own thread (assume A thread) work slow,the main thread will finish,so main response will return to user.and the A thread must continue work properly,I will request the response of the A thread using AJAX in browser side later.

So,I want to clone the HttpServlettRequest and HttpServletResponse provided by the Servlet Container,and the cloned request and response must be detached(When container's HttpServletTrequest and HttpServletResponse finished,the cloned request and reponse still work properly).

The behave of the cloned request and response must be same as the Container's from my code's view.It can be followed and included.

Any idea?

Thanks very much!

L.J.W

like image 542
L.J.W Avatar asked Mar 11 '11 13:03

L.J.W


2 Answers

Cloning HTTP request and response is possible via HttpServletResponseWrapper class http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletResponseWrapper.html. You can find an example of usage on Sun documentation https://web.archive.org/web/20120626033905/http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets8.html.

Notice this was a workaround from (at that time) Sun to address this problem as it was never planned that you could modify request and response information before committed.

You can use the wrapper to make a copy of Http information and the pass it to a different thread.

like image 200
Juan C Avatar answered Oct 09 '22 02:10

Juan C


Sounds like you need to create classes to act as a delegate to the HttpRequest and HttpResponse objects and then pass a reference to on to a Runnable object to process.

There are certain operations that can only be done once to an HttpRequest object ( reading from the inputstream springs to mind ), the delegate class would have to cater for this.

Not sure what you're going to do if the A, B and C threads make conflicting changes to the HttpResponse object though.

I think I'd prefer to not pass the HttpResponse object through to the processing threads and leave the logic for populating the response in the controlling servlet class

like image 23
DaveH Avatar answered Oct 09 '22 00:10

DaveH