Java servlet中的ImageIO:我应该关闭输出流吗?如何设置内容长度?

Java servlet中的ImageIO:我应该关闭输出流吗?如何设置内容长度?,java,servlets,jetty,javax.imageio,jetty-9,Java,Servlets,Jetty,Javax.imageio,Jetty 9,我正在使用Jetty 9.4.21.v20190926-作为HAProxy背后的独立服务器,并使用它编译/运行我的自定义WAR servlet: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd"> <Configure clas

我正在使用Jetty 9.4.21.v20190926-作为HAProxy背后的独立服务器,并使用它编译/运行我的自定义WAR servlet:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" 
    "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Set name="contextPath">/mypath</Set>
    <Set name="war">
        <SystemProperty name="jetty.base"/>/my-servlet-0.1-SNAPSHOT.war
    </Set>
</Configure>
问题1:我应该明确设置内容长度,还是Jetty会自动为我添加内容长度?如果我必须自己设置,如何处理动态gzip压缩导致的大小变化


问题2:我应该在doGet()的末尾调用
httpResp.getOutputStream().close()
,还是因为Keep Alive,仍然需要输出流来处理其他请求?

1。你没有。您可以让servlet来完成。或者使用分块或固定长度的传输编码。2.对当然,这里根本不需要使用ImageIO。只需复制字节。使用这种方法会浪费很多时间和内存。谢谢。顺便说一句,我不是在浪费时间,我刚刚展示了我的程序的一个简单版本,它从几个图像+文本中绘制出一个合成的PNG。
@Override
protected void doGet(HttpServletRequest httpReq, HttpServletResponse httpResp) throws ServletException, IOException {
    if ("board1".equals(httpReq.getServletPath()) {
        BufferedImage image = ImageIO.read(org.eclipse.jetty.util.Loader.getResource("game_board_1.png"));
        // in the real app: more images + text drawing happens here
        httpResp.setStatus(HttpServletResponse.SC_OK);
        httpResp.setContentType("image/png");
        httpResp.setContentLength(12345); // question 1: should I call this or will Jetty add it automatically?
        ImageIO.write(image, "png", httpResp.getOutputStream());
        httpResp.getOutputStream().close();  // question 2: should I close the output stream here or not?
    }
}