[jdom-interest] Re: JDOM via Servlet

Joseph Bowbeer jozart at csi.com
Tue Jul 24 00:44:34 PDT 2001


Oops.  I answered too quickly.  A couple of corrections:

Forget about #4.  I was thinking byte[] buf (not char[] buf)...

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
sent.

I also missed that you *are* reading the response before disconnecting.  I
guess that leaves #3 about br.read(buf) only doing a partial read as the
most significant trouble spot.

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

Once again, I'll contribute a simple servlet example if I find the time.


----- Original Message -----
From: "Joseph Bowbeer" <jozart at csi.com>
To: <jdom-interest at jdom.org>
Cc: "John Muhlestein" <jmuhlestein at i-link.net>
Sent: Tuesday, July 24, 2001 12:06 AM
Subject: JDOM via Servlet


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);
    cxn.disconnect();
    return fromServlet;

There's also some suspicious code in your servlet:

    char[] buf = new char[request.getContentLength()];
    BufferedReader br = new BufferedReader(request.getReader());
    br.read(buf);
    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
sent.

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