簡體   English   中英

Servlet過濾器與CXF攔截器之間用於修改請求和響應內容?

[英]Servlet filter vs. CXF interceptor for modifying request & response content?

我們使用Apache CXF構建了一些REST(jax-rs)Web服務。 他們返回JSON響應。

我現在需要修改一些請求參數和響應內容。 (基本上我們需要對服務返回的一些數據進行編碼/加密;當在后續服務調用中將其用作參數時,解碼/解密相同的數據。)

看來我這里至少有4個選項:

  1. 使用Servlet過濾器
  2. 使用CXF攔截器
  3. 使用JAX-RS過濾器
  4. 不要使用任何特定模式,並在實際服務邏輯中執行編碼/解碼。

我之前使用過Servlet過濾器,並且確切地了解如何修改請求參數和響應體,所以我傾向於此。 但是,我願意使用CXF Interceptor或JAX-RS過濾器,如果這是使用CXF時解決此問題的更“正確”的方法。 但根據文檔,我真的不明白如何做到這一點。 例如,我是否使用Message對象的setContent方法來更改JSON響應? 在這種情況下,格式參數是什么,只是String.class?

在這里回答我自己的問題...我最終使用了一個JAX-RS過濾器,一旦我找到了缺少文檔,它運行良好。 我使用了http://cxf.apache.org/docs/jax-rs-filters.html中的(相當稀疏的)文檔。 注意盡管它的名字,JAX-RS過濾器是特定於CXF的野獸,不是JAX-RS標准的一部分(據我所知)。

這是一些示例代碼:

@Context
private HttpServletRequest httpRequest;
@Context
private UriInfo uriInfo;

/**
 * @see org.apache.cxf.jaxrs.ext.ResponseHandler#handleResponse(org.apache.cxf.message.Message, org.apache.cxf.jaxrs.model.OperationResourceInfo, javax.ws.rs.core.Response)
 */
public Response handleResponse(Message message, OperationResourceInfo opResourceInfo, Response response) {
    try {

        // log the injected context data; useful for debugging CXF problems
        logContextData(httpRequest, uriInfo);

        OutputStream os = message.getContent(OutputStream.class);
        String relevantData = getDataFromRequest(httpRequest);
        message.setContent(OutputStream.class, new MyOutputStreamWrapper(os, relevantData));

    } catch (CustomException e) {
            // return some status that is related to CustomException
        return Response.status(Status.UNAUTHORIZED).build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    return response;
}

/**
 * @see org.apache.cxf.jaxrs.ext.RequestHandler#handleRequest(org.apache.cxf.message.Message, org.apache.cxf.jaxrs.model.ClassResourceInfo)
 */
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    try {

        // log the injected context data; useful for debugging CXF problems
        logContextData();

        String updatedQueryString = buildNewQueryString(this.uriInfo, httpRequest);

        message.put(Message.QUERY_STRING, updatedQueryString);


        // returning null tells CXF to continue the request (i.e. a non-null value would halt the request)
        return null;

    } catch (CustomException e) {
        // return some status that is related to CustomException
        return Response.status(Status.UNAUTHORIZED).build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

我應該注意,MyOutputStreamWrapper的實現是修改響應內容的重要部分。 由於安全考慮,我無法在此處包含該源(實際上我的實現具有不同的名稱)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM