gpt4 book ai didi

java - 我如何将参数添加到 Jersey 过滤器请求(ContainerRequestFilter)的请求

转载 作者:搜寻专家 更新时间:2023-10-31 20:20:56 25 4
gpt4 key购买 nike

我正在使用 Jersey + Spring。我有实现 ContainerRequestFilter 的 Jersey 过滤器,我需要在我的 jersey 资源中传输对象。

例如:

@Provider

public class UnmarshalEntityFilter implements ContainerRequestFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(UnmarshalEntityFilter.class);

@Override
public ContainerRequest filter(ContainerRequest containerRequest) {

final String xml = getRequestBody(containerRequest);
// Parse this xml to Object

// How I can add this Object to my request and get from Jersey Resource ?

return containerRequest;
}

private String getRequestBody(ContainerRequest request) {

ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = request.getEntityInputStream();
StringBuilder sb = new StringBuilder();
try {
if (in.available() > 0) {
ReaderWriter.writeTo(in, out);

byte[] requestEntity = out.toByteArray();
sb.append(new String(requestEntity, "UTF-8"));
}

return sb.toString();
} catch (IOException ex) {
throw new ContainerException(ex);
}

}

最佳答案

参见 ContainerRequest#setProperty(String, Object) 说明方法

In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

所以你可以简单地调用

final String xml = getRequestBody(containerRequest);
containerRequest.setProperty("xml", xml);

然后注入(inject) HttpServletRequest在你的处理程序中并使用 HttpServletRequest#getAttribute("xml") 访问它.

Jersey 1.17,对应的方法是 ContainerRequest#getProperties() 它返回一个可变的 Map<String, Object>您可以将与 ServletRequest 同步的属性放入其中.

您可以从 HttpContext 检索 Jersey 资源中的属性:

@Context
private HttpContext httpCtx
...
final String xml = httpCtx.getProperties().get("xml")

换句话说,小心使用请求 InputStream .如果堆栈中的某些其他组件也需要从流中读取,它将失败。

关于java - 我如何将参数添加到 Jersey 过滤器请求(ContainerRequestFilter)的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18876053/

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