gpt4 book ai didi

java - 在 JAX-RS WriterInterceptor 和 ReaderInterceptor 之间传递参数

转载 作者:行者123 更新时间:2023-12-02 09:08:18 24 4
gpt4 key购买 nike

我正在使用 JAX-RS,并且在 WriterInterceptor 中,我需要访问原始请求中包含的一些信息。

作为示例,请考虑以下请求正文。

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

在我的 WriteInterceptor 中,我需要从请求中读取客户端 ID用户 ID 并将这些值添加到响应中。

我目前正在为此开发 ReadInterceptor 实现。我最初假设有一种方法可以将参数放入 ReaderInterceptorContext 中,然后以某种方式从 WriterInterceptorContext 中读取它。但似乎没有办法做到这一点。 (如果我错了,请纠正我)。

所以,现在我尝试使用并发 HashMap 将这些参数存储在 ReaderInterceptor 中并在 WriteInterceptor 中检索它。我需要一个唯一的 key 来创建请求和响应之间的关联。是否可以使用线程 ID 来实现此目的?

如果有更好的方法来解决这个问题,请指出

最佳答案

我通过添加 container response filter 解决了这个问题它可以向响应添加 header 。读取拦截器从请求中读取所需的参数并将其设置为上下文属性

    @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();
}

然后在容器响应过滤器内读取这些属性,并将其添加为响应 header

@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"));
}

现有的编写器拦截器读取这些 header ,将它们添加到 JWT,然后作为 header 值删除。我为此做了一个 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();
}

关于java - 在 JAX-RS WriterInterceptor 和 ReaderInterceptor 之间传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com