Wednesday, July 18, 2007

NullPointerException tomcat5 realWriteChars

Keywords:
NullPointerException tomcat5 realWriteChars servlet

Problem:
Getting this stack trace on each access of a servlet:

java.lang.NullPointerException
 at org.apache.coyote.tomcat5.OutputBuffer.realWriteChars(OutputBuffer.java:569)
 at org.apache.tomcat.util.buf.CharChunk.flushBuffer(CharChunk.java:435)
 at org.apache.tomcat.util.buf.CharChunk.append(CharChunk.java:366)
 at org.apache.coyote.tomcat5.OutputBuffer.write(OutputBuffer.java:516)
 at org.apache.coyote.tomcat5.CoyoteWriter.write(CoyoteWriter.java:149)
 at org.apache.coyote.tomcat5.CoyoteWriter.write(CoyoteWriter.java:158)
 at org.apache.coyote.tomcat5.CoyoteWriter.print(CoyoteWriter.java:208)
 at org.apache.coyote.tomcat5.CoyoteWriter.println(CoyoteWriter.java:265)
 at com.example.MyServlet.doGet(MyServlet.java:56)


The line number in "MyServlet" code that's kicking this off is a simple PrintWriter.println() ... what it's writing to the stream is definitely not null. How could a NPE be caused in tomcat?

Solution:
I wouldn't have guessed at the issue if not trying the same servlet on WebSphere ... then you get a more useful error message:
Invalid character encoding "UTF=8"

There's a typo (ie '=' instead of '-') in the call to set the content type on the HttpResponse object! Correcting this to "UTF-8" fixes the issue:
response.setContentType("text/html; charset=UTF-8");

No comments: