javaembedded-tomcat

How do I customize embedded Tomcat’s error pages programmatically?


I am using programmatic configuration of an Embedded Tomcat server very similar to Heroku’s example here.

I supply my own Servlet class to Tomcat using this approach.

How can I customize the error pages that Tomcat renders?


Solution

  •   public void configureErrorPages(StandardContext ctx) {
        ErrorPage error404 = new ErrorPage();
        error404.setLocation("/errors/404");
        error404.setErrorCode(HttpServletResponse.SC_NOT_FOUND);
        ctx.addErrorPage(error404);
    
        ErrorPage error500 = new ErrorPage();
        error500.setLocation("/errors/500");
        error500.setErrorCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ctx.addErrorPage(error500);
      }
    

    This is using org.apache.catalina.core.StandardContext, org.apache.tomcat.util.descriptor.web.ErrorPage, and jakarta.servlet.http.HttpServletResponse. With the above configuration, on a 404, Tomcat will dispatch a second request to /errors/404. Your servlet can react to it with a custom error page. Similarly with the 500 error. This was adapted from some spring-boot code.

    There are no xmls to write with this approach.