1

I have implemented the following servlet post function on a jetty server. In the HttpServletResponse, it will just write some string.

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write("some json string");
    response.getWriter().flush();
}

Everything was fine in the beginning. But after some time (a few days; i was not using it and just kept the jetty server running), the servlet starts to throw null pointer exception on the line response.getWriter().write("some json string");

java.lang.NullPointerException
        at org.eclipse.jetty.server.ResponseWriter.write(ResponseWriter.java:246)

I don't know what went wrong. But after a restart of the jetty server, the problem was gone. Do you guys know why?

Jeff
  • 27
  • 5

1 Answers1

0

To answer the NullPointerException

java.lang.NullPointerException
        at org.eclipse.jetty.server.ResponseWriter.write(ResponseWriter.java:246)

It seems that you gave the Writer a null String.

See: https://github.com/eclipse/jetty.project/blob/jetty-9.4.22.v20191022/jetty-server/src/main/java/org/eclipse/jetty/server/ResponseWriter.java#L246

The part where you say Jetty stops working after a few days is likely because you have a process on your machine that is periodically cleaning out the system temp directory, removing content out from underneath Jetty.

See: Jetty stops responding after some period of time

The NullPointerException is like is likely because the write failed and you didn't check for that fact.

HttpServletResponse.getWriter() returns a java.io.PrintWriter.

Using the various .write() methods will never throw an error or exception.

You need to use .checkError() method to know when the write has failed.

This is an old-school API decision on java.io.PrintWriter that is actually quite awkward.

See: PrintWriter and PrintStream never throw IOExceptions

Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136