Disable all default HTTP error response content in Tomcat

If you do not want tomcat to show an error page, then do not use sendError(…). Instead use setStatus(…).

e.g. if you want to give a 405 response, then you do

response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);      
response.getWriter().println("The method " + request.getMethod() + 
   " is not supported by this service.");

Also remember not to throw any Exceptions from your servlet. Instead catch the Exception and, again, set the statusCode your self.

i.e.

protected void service(HttpServletRequest request,
      HttpServletResponse response) throws IOException {
  try {

    // servlet code here, e.g. super.service(request, response);

  } catch (Exception e) {
    // log the error with a timestamp, show the timestamp to the user
    long now = System.currentTimeMillis();
    log("Exception " + now, e);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().println("Guru meditation: " + now);
  }
}

of course, if you do not want any content, then just don’t write anything to the writer, just set the status.

Leave a Comment