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

前端之家收集整理的这篇文章主要介绍了java – 如何从泽西过滤器请求(ContainerRequestFilter)添加参数来请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用泽西春天.我有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.如果堆栈中的某些其他组件也需要从流中读取,则它将失败.

猜你在找的Java相关文章