2011-06-30 26 views
0

我試圖實現一個服務器端API方法,該方法允許一批API請求作爲單個請求的一部分來執行,批量中的每個請求的響應都包含在返回給客戶端的JSONArray中。Servlets - 如何引入()資源並獲得其作爲字符串的響應?

在本質上,客戶端調用服務器與沿着線「分批」參數:

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

這指定了一個由兩個API調用批次。我想要做的就是執行各一臺,以及響應合併成類似:

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

執行批處理,我反覆呼籲RequestDispatcher.include(),因爲這樣的:

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'? 
} 

一切運作良好(所有的批處理請求都會被執行,並且服務器會正​​確處理它們),但我無法弄清楚如何獲取包含的響應,以便將其添加到結果數組中。

任何想法?

回答

2

我會首先嚐試避免處理個別請求時通過servlet堆棧。你不能直接調用一些業務方法嗎?我明白你想重新使用調度和參數解析邏輯,但也許那部分不是很複雜。

如果這是不可能的,也許您可​​以將request.setAttribute("theResult", jsonData)添加到各個處理程序中,以便您不必查看文本結果,但可以更輕鬆地檢索數據。

如果您仍想查看響應流,則需要創建ResponseWrapper。例如,檢出this question

+0

在這種情況下,我傾向於通過servlet堆棧,因爲存在一定比例的訪問權限檢查邏輯,它處理的是我不希望重新實現或摺疊到業務方法本身。基本上每個業務方法都用一組必須滿足的約束進行註釋,以允許調用該方法,並且在servlet堆棧中有一些與驗證這些約束相關的通用代碼。無論如何,響應包裝看起來是一個很好的解決方案,但我試過了,響應不斷以一個空字符串的形式返回。有任何想法嗎? – aroth

+0

沒有關於作家的最後一點。在嘗試訪問數據之前,我需要手動調用'flush()'。問題解決了。 – aroth

相關問題