4 Replies Latest reply on Dec 21, 2005 12:41 PM by ashisha

    how to get the number of bytes sent by the servlet response

    ashisha

      Hi,

      I want to know how many bytes my servlet reponse has sent back to the client. My client and server exachange objects using object input / output streams. Is there an api that can give me the bytes the servlet engine / web server has sent back to the client in a request?

      Thanks in advance,
      Ashish

        • 1. Re: how to get the number of bytes sent by the servlet respo
          nigelwhite

          There's lots of ways. If you want every servlet counted, you can write a javax.servlet.Filter (You can filter depending on URL pattern so you can be selective if you want) which passes an HttpServletResponseWrapper which you would write along the filter chain.

          This wrapper's getOutputStream() method would return an OutputStream subclass of your own making which counts bytes written.

          getWriter() would use getOutputStream().

          You would then declare your filter in your web.xml descriptor.

          If it's just one servlet that you are fully in control of, then don't call out.write() directly, call it through a method which counts the bytes.

          • 2. Re: how to get the number of bytes sent by the servlet respo
            ashisha

            Thanks for the response NigelWhite,

            Sorry, I forgot to mention the following:

            1. I have just one servlet
            2. I do not want to go byte by byte in the stream, this will slow down my response

            I see in the status page of the tomcat, the number of bytes in request and response. Not sure how that is calculated. I want to know if there is an api in tomcat that can help me get the bytes.

            Thanks again

            • 3. Re: how to get the number of bytes sent by the servlet respo
              nigelwhite

              Just send all output through a method!

              private int responseLength = 0; // zero it at the start of your code!!!
              
              private void write(OutputStream out, String data)
              {
               responseLength += data.length;
               out.write(data);
              }
              


              What's wrong with that?

              • 4. Re: how to get the number of bytes sent by the servlet respo
                ashisha

                Hi NigelWhite,

                I have a complex object and not s String. I do not want to count byte by byte, as that will take time.. Hence, wondering if there is a readymade api in tomcat that i can access.

                Thanks for all your help...