0

I am using Jetty 9.4.21.v20190926 - as a standalone server behind HAProxy and also I compile/run my custom WAR servlet with it:

<?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>

It serves Websockets, GET, POST requests and works very well over the last 2 years.

Now I would like additionally to generate a PNG file using ImageIO and while the code below works for me, I have 2 questions please -

@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?
    }
}

Question 1: Should I explicitly set Content-Length or will Jetty add it automatically for me? And if I have to set it myself, how to deal with the changed size because of on the fly gzip-compression?

Question 2: Should I call httpResp.getOutputStream().close() at the end of doGet() or maybe the output stream is still needed to serve other requests, because of Keep-Alive?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
  • 2
    1. You don't. You let the servlet do it. Or else you use chunked or fixed-length transfer encoding. 2. Yes. Of course you don't need to use ImageIO here at all. Just copy the bytes. You're wasting a lot of time and memory with this approach. – user207421 Oct 04 '19 at 10:11
  • 1
    Thanks. By the way I am not wasting time, I have just shown a simple version of my program which draws a composed PNG out of several images + text. – Alexander Farber Oct 04 '19 at 12:14
  • 1
    https://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter – Harald K Oct 07 '19 at 14:52

0 Answers0