是否可以将Jersey JSP模板响应重新路由到InputStream?

时间:2011-09-22 14:51:43

标签: java jsp jersey jax-rs

所有

我使用Java / Jersey 1.9创建一个生成XML的Web服务。我正在使用JSP模板生成XML(显式地通过Viewable类)。有没有办法将JSP结果重新路由到本地InputStream以进行进一步处理?目前,我实际上是从另一种方法调用我自己的XML Web服务作为http loopback(localhost)。

感谢您的任何见解,

伊恩

@GET @Path("kml")
@Produces("application/vnd.google-earth.kml+xml")
public Viewable getKml(
        @QueryParam("lat") double lat,
        @QueryParam("lon") double lon,
        @QueryParam("alt") double alt) {

    overflights = new SatelliteOverflightModel(
            context, new SatelliteOverflightModel.Params(lat, lon, alt)
            ).getOverflights();

    return new Viewable("kml", this);
}

@GET @Path("kmz")
@Produces("application/vnd.google-earth.kmz")
public InputStream getKmz(@Context UriInfo uriInfo,
        @QueryParam("lat") double lat,
        @QueryParam("lon") double lon,
        @QueryParam("alt") double alt)
        throws IOException {

    Client client = Client.create();
    WebResource webr = 
            client.resource(uriInfo.getBaseUri()+"overflights/kml");
    InputStream result =
            webr.queryParams(uriInfo.getQueryParameters()).get(InputStream.class);

    // Do something with result; e.g., add to ZIP archive and return

    return result;
}

1 个答案:

答案 0 :(得分:0)

您可以考虑使用ContainerResponseFilter而不是资源 - 请参阅例如Gzip filter泽西岛提供。不同之处在于您的过滤器将依赖于Accept和Content-Type标头而不是Accept-Encoding和Content-Encoding标头(如gzip过滤器那样)。

如果您坚持使用资源,可以在资源上注入Providers接口,找到正确的MessageBodyWritter并在其上调用write方法:

@GET @Path("kmz")
@Produces("application/vnd.google-earth.kmz")
public InputStream getKmz(@Context UriInfo uriInfo,
        @QueryParam("lat") double lat,
        @QueryParam("lon") double lon,
        @QueryParam("alt") double alt,
        @Context Providers providers,
        @Context HttpHeaders headers)
        throws IOException {

    Viewable v = getKml(lat, lon, alt);
    MessageBodyWriter<Viewable> w = providers.getMessageBodyWriter(Viewable.class, Viewable.class, new Annotation[0], "application/xml");
    OutputStream os = //create the stream you want to write the viewable to (ByteArrayOutputStream?)
    InputStream result = //create the stream you want to return
    try {
        w.writeTo(v, v.getClass(), v.getClass(), new Annotation[0], headers, os);
        // Do something with result; e.g., add to ZIP archive and return
    } catch (IOException e) {
        // handle
    }
    return result;
}

免责声明:这是我的头脑 - 未经测试:)