加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何从泽西过滤器请求(ContainerRequestFilter)添加参数

发布时间:2020-12-14 19:36:37 所属栏目:Java 来源:网络整理
导读:我用泽西春天.我有Jersey过滤器,它实现了ContainerRequestFilter,我需要在我的球衣资源中传输对象. 例如: @Providerpublic class UnmarshalEntityFilter implements ContainerRequestFilter {private static final Logger LOGGER = LoggerFactory.getLogger
我用泽西春天.我有Jersey过滤器,它实现了ContainerRequestFilter,我需要在我的球衣资源中传输对象.

例如:

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

然后在你的处理程序中注入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.如果堆栈中的某些其他组件也需要从流中读取,则它将失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读