[jdom-interest] JDOM via Servlet

Joseph Bowbeer jozart at csi.com
Tue Jul 24 00:06:59 PDT 2001

John Muhlestein writes:

> I seem to continue to be running up against a brick wall trying
> to pass XML to a servlet and then building a JDOM Document ...

Looking at your code, the biggest problem I see is that you're disconnecting
your connection before reading the response from the servlet:

  public InputStream send (ByteArrayOutputStream content)
  throws Exception {
    /* ... */
    InputStream fromServlet = new ByteArrayInputStream(buf);
    return fromServlet;

There's also some suspicious code in your servlet:

    char[] buf = new char[request.getContentLength()];
    BufferedReader br = new BufferedReader(request.getReader());
    StringReader sr = new StringReader(String.valueOf(buf));

As follows:

1. Sockets operate on bytes not chars.

2. The content length is the number of bytes, not the number of chars.  If
your content is UTF8 encoded, for example, then the content length will be
greater than the number of chars unless all the character content lies
within the ASCII range.

3. br.read(buf) will read *some* characters, but not necessarily all of
them.  DataInputStream.readFully, on the other hand, will read everything.

4. String.valueOf(buf) uses the default character decoder on your servlet's
platform, which may not match the encoder that was used when the request was

Do this instead:

    byte[] buf = new byte[request.getContentLength()];
    new DataInputStream(request.getInputStream()).readFully(buf);
    InputStream in = new ByteArrayInputStream(buf);
    Document doc = new SAXBuilder().build(in);

If I find some time later, I'll send a complete JDOM client/servlet sample.

Joe Bowbeer

More information about the jdom-interest mailing list