簡體   English   中英

在 JAX-RS WriterInterceptor 和 ReaderInterceptor 之間傳遞參數

[英]Passing parameters between JAX-RS WriterInterceptor and ReaderInterceptor

我正在使用 JAX-RS 並且在 WriterInterceptor 中,我需要訪問原始請求中包含的一些信息。

例如,請考慮以下請求正文。

{ 
        "ClientId": "MY_CLIENT_ID",
        "UserId": "MY_USER_ID",
        "AccountId": "MY_ACCOUNT_ID",
        "Scope" : "MY_SCOPES",
}

在我的WriteInterceptor 中,我需要從請求中讀取客戶端 ID用戶 ID ,並將這些值添加到響應中。

我目前正在為此研究 ReadInterceptor 實現。 我最初假設有一種方法可以將參數放入ReaderInterceptorContext ,然后以某種方式從WriterInterceptorContext讀取它。 但似乎沒有辦法做到這一點。 (如果我錯了,請糾正我)。

所以,現在我正在嘗試使用並發散列圖將這些參數存儲在 ReaderInterceptor 中並在 WriteInterceptor 中檢索它。 我需要一個唯一的鍵來創建請求和響應之間的關聯。 可以為此使用線程 ID嗎?

請指出是否有更好的方法來解決此問題

我通過添加一個容器響應過濾器解決了這個問題,該過濾器可以向響應添加一個標頭。 讀取攔截器從請求中讀取所需的參數並將它們設置為上下文屬性

    @Override
     public Object aroundReadFrom(ReaderInterceptorContext   readerInterceptorContext)
        throws IOException, WebApplicationException {

    InputStream is = readerInterceptorContext.getInputStream();
    String requestBody = new Scanner(is, StandardCharsets.UTF_8.name()).useDelimiter("\\A").next();
    JSONObject request = new JSONObject(requestBody);
    //Adding the stream back to the context object
    readerInterceptorContext.setInputStream(new ByteArrayInputStream(requestBody.getBytes()));
    //Adding properties to read in filter
    readerInterceptorContext.setProperty("ClientId", request.get("ClientId"));
    readerInterceptorContext.setProperty("UserId","UserId"));
    return readerInterceptorContext.proceed();
    }

然后在容器響應過濾器中讀取這些屬性並將其添加為響應標頭

@Override
public void filter(ContainerRequestContext containerReqContext, ContainerResponseContext containerResponseContext) {
    //Adding temporary headers to read in WriterInterceptor
    containerResponseContext.getHeaders().add(
            "ClientId", containerReqContext.getProperty("ClientId"));
    containerResponseContext.getHeaders().add(
            "UserId", containerReqContext.getProperty("UserId"));
}

現有的編寫器攔截器讀取這些標頭,將它們添加到 JWT,然后作為標頭值刪除。 我為此做了一個 POC,它按預期工作

    @Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException {
    OutputStream outputStream = writerInterceptorContext.getOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writerInterceptorContext.setOutputStream(baos);
    String clientId = writerInterceptorContext.getHeaders().getFirst("ClientId").toString();
    String user = writerInterceptorContext.getHeaders().getFirst("UserId").toString();   
}

暫無
暫無

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

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