aroth
aroth

Reputation: 54796

Servlets - How to inlude() a resource and get its response as a String?

I'm trying to implement a server-side API method that allows a batch of API requests to be executed as part of a single request, with the response for each request in the batch wrapped into a JSONArray that is returned to the client.

In essence, the client calls the server with a "batch" parameter along the lines of:

[{method: "getStatus" userId: "5"}, {method: "addFriend", userId: "5", friendId: "7"}]

This specifies a batch composed to two API calls. What I want to do is execute each one, and combine the responses into something like:

[{status: "success", status: "At work..."}, {status: "error", message: "Friend not found!"}]

To execute the batch, I am iteratively calling RequestDispatcher.include(), as such:

String format = request.getParamter("format");  //carry the requested response format forward for each batched request
JSONArray batchResponse = new JSONArray();
RequestDispatcher dispatcher = request.getRequestDispatcher("/apiContext");
OverridableHttpRequest reusableRequest = new OverridableHttpRequest(request);
JSONArray requests = (JSONArray)JSONValue.parse(request.getParameter("batch"));
for (Object batchedRequest : requests) {
    reusableRequest.reset();  //clear all params and attribs

    //set the parameters to use for this request
    JSONObject requestParams = (JSONObject)batchedRequest;
    for (Object key : requestParams.keySet()) {
        reusableRequest.setParameter(key.toString(), requestParams.get(key).toString());
    }
    reusableRequest.setParameter("format", format);

    LOG.debug("including:  /apiContext?" + reusableRequest.getQueryString());

    //process the request as if it were received normally
    dispatcher.include(reusableRequest, response);  //FIXME:  how to get the response data for this include into 'batchResponse'?
}

Everything works well (all the batched requests are executed, and the server processes them correctly), but I can't figure out how to get the included response out so that I can add it to the results array.

Any ideas?

Upvotes: 0

Views: 218

Answers (1)

Thilo
Thilo

Reputation: 262474

I would first try to avoid going through the servlet stack when handling the individual requests. Cannot you just call some of your business methods directly? I appreciate that you want to re-use the dispatching and parameter parsing logic, but maybe that part is not very complicated.

If that is not possible, maybe you can add a request.setAttribute("theResult", jsonData) into the individual handlers, so that you do not have to look at the text result, but can retrieve the data more easily.

If you still want to look at the response stream, you need to create a ResponseWrapper. For example check out this question.

Upvotes: 2

Related Questions