3

我无法让 ChunkedOutput 使用 JAX-RS Jersey 2.3.1 和 Tomcat 7 工作。我正在尝试遵循Jersey Tutorial - Chapter 10. Asynchronous Services and Clients中的教程

我的代码如下所示

@GET
@Path("/asynchronous")
public ChunkedOutput<String> getAsyncResponse() {

    final ChunkedOutput<String> output = new ChunkedOutput<String>(String.class);

    new Thread() {
        public void run() {
            try {
                String text;
                for (int i = 0; i < 20; i++) {
                    text = String.valueOf(i);
                    output.write(text);
                    Thread.sleep(1000);
                }
            } catch (Throwable th) {
                th.printStackTrace();
            } finally {
                try {
                    output.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }.start();

    return output;
}

当我尝试通过 curl 或我的 Java 客户端调用它时,我在 Web 服务端遇到了以下异常。

org.glassfish.jersey.server.internal.process.MappableException: java.lang.NullPointerException
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:96)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:149)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1139)
    at org.glassfish.jersey.server.ChunkedOutput$1.call(ChunkedOutput.java:148)
    at org.glassfish.jersey.server.ChunkedOutput$1.call(ChunkedOutput.java:121)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:242)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:345)
    at org.glassfish.jersey.server.ChunkedOutput.flushQueue(ChunkedOutput.java:121)
    at org.glassfish.jersey.server.ChunkedOutput.write(ChunkedOutput.java:111)
    at jaxrs.prototype.tomcat7.AsyncPrototype$1.run(AsyncPrototype.java:82)
Caused by: java.lang.NullPointerException
    at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
...

知道出了什么问题吗?最初我将它部署在 Tomcat 6 上,然后我意识到异步功能在 Servlet 3.0 API 中可用,而 Tomcat 6 不支持,因此我切换到 Tomcat 7。

4

1 回答 1

1

在 web.xml 中添加 async-supported 对我有用。之后我不再看到异常。

尽管我的客户端仍然存在问题,每次写入时它都没有接收到分块输出。相反,它在最后一次接收所有分块输出。

  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>jaxrs.prototype;org.codehaus.jackson.jaxrs</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
于 2013-10-09T05:17:40.100 回答