Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [jetty-users] ImageIO in servlet: should I close the httpResp.getOutputStream() and how to set Content-Length?

It looks like you're reading the whole png before sending, where you could save latency and memory for big files and have a good general method by using the static resource servlet given here:

http://stackoverflow.com/questions/132052/servlet-for-serving-static-content

Bill

On 10/4/19 2:04 AM, Alexander Farber wrote:
Good morning,

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

It serves Websockets, GET, POST requests and works very well, thank you!

However now I would like 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(getResource("ru/game_board_1.png"));
            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 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?

Thank you
Alex

PS: Below is my very simple config file:

<?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">/ws</Set>
    <Set name="war"><SystemProperty name="jetty.base"/>/../WebSockets/target/ws-servlet-0.1-SNAPSHOT.war</Set>
</Configure>


_______________________________________________
jetty-users mailing list
jetty-users@xxxxxxxxxxx
To change your delivery options, retrieve your password, or unsubscribe from this list, visit
https://www.eclipse.org/mailman/listinfo/jetty-users

Back to the top