Servlet process data after response was sent

292 views Asked by At

For some reason there are no request headers in HttpServletRequest when I try to acces them in a separate thread like here:

new Thread() {
    public void run() {
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String header_name = headerNames.nextElement();
                System.out.println("Header: " + request.getHeader(header_name));

            }
        }
    }
}.start();

I want to process some data in that thread asynchronously.

When I put the code outside of the thread, it works.

1

There are 1 answers

2
Kevin Boone On

The "usual" implementation of a servlet engine has the request and response objects created at the start of the request-handling process, that is, before the call to service(). I would expect these objects to have a longer lifetime than the request itself. Therefore, the fact that the request object has no headers looks odd to me. However, I don't know why that would happen, and I think it would be difficult to work out without seeing a test case.

But...

Once the request has completed, there is no way for the spawned thread to communicate with the client/browser. Any work carried out in this thread is invisible to the client. It is thus completely independent of the request-response flow and, in my view, should have its own API, rather than being dependent on the whims of the servlet container.

So my approach would be to define a Java class that contains all the data needed for the asynchronous thread to do whatever it does, and copy all the relevant data into a new instance of that class during the request handling process (in doGet(), etc). Then pass the new instance to the asynchronous thread. This thread is thus completely decoupled from the mechanics of handling a servlet request.

It should go without saying that spawning new threads from a Servlet -- although legal -- is fraught with difficulties. A lot of careful attention has to be given to matters of synchronization.