@ResponseBody 导致 EofException

JJe*_*nsL 5 java spring spring-mvc

我有一个 Spring MVC 控制器,它通过 @ResponseBody 注释返回一段 HTML(作为字符串)。下面看一下方法签名:

@RequestMapping(value="/weather", method=RequestMethod.GET, produces="text/html")
@ResponseBody
public String getWeatherForcast(HttpServletResponse response)
Run Code Online (Sandbox Code Playgroud)

从嵌入式 Jetty 实例运行应用程序时,我得到了预期的 HTML 响应,但是,应用程序服务器日志为每个请求抛出以下堆栈跟踪:

org.eclipse.jetty.io.EofException
        at org.eclipse.jetty.server.HttpOutput.flush(HttpOutput.java:137)
        at ch.qos.logback.access.servlet.TeeServletOutputStream.flush(TeeServletOutputStream.java:85)
        at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297)
        at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
        at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
        at org.springframework.util.StreamUtils.copy(StreamUtils.java:107)
        at org.springframework.http.converter.StringHttpMessageConverter.writeInternal(StringHttpMessageConverter.java:106)
        at org.springframework.http.converter.StringHttpMessageConverter.writeInternal(StringHttpMessageConverter.java:40)
        at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
        at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148) ...
Run Code Online (Sandbox Code Playgroud)

查看 Jetty 代码后,它抛出此异常是因为请求上的套接字连接已关闭。

也就是说,我注意到如果我直接使用 Response 对象(下面的代码段),我会得到相同的结果,但没有 EofException。

@RequestMapping(value="/weather", method=RequestMethod.GET, produces="text/html")
public void getWeatherForcast(HttpServletResponse response) {     
     ....

response.getWriter().write(xpathTemplate.evaluateAsString("/rss/channel/item/description",result));
   response.flushBuffer();
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么 Spring @ResponseBody 方法会导致套接字过早关闭,以及是否有办法克服这个问题。

JJe*_*nsL 1

我明白了这一点。我使用 Maven Cargo 插件(版本 1.3.3)来运行我的嵌入式 Jetty 实例。Cargo 版本 1.3.3 使用嵌入式 Jetty 容器的候选发布版本 (v 9.0.0-RC0)。

我尝试将 Cargo 插件升级到使用 Jetty 9.0.5 的版本 1.4.4,并且 EofException 消失了。