How does Tomcat handle error pages?

There are two ways to handle error pages in Tomcat.

  1. Setting error pages using web.xml: In the web.xml file, you can configure global error pages as well as error pages corresponding to specific error codes. For example:
<error-page>
    <error-code>404</error-code>
    <location>/error/404.html</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/error/500.html</location>
</error-page>
  1. Using Servlet to handle error pages: You can customize a Servlet to handle error pages by implementing the javax.servlet.ErrorPage interface, to handle various error page scenarios. For example:
@WebServlet("/errorHandler")
public class ErrorHandlerServlet extends HttpServlet implements ErrorPage {

    @Override
    public void handleErrorPage(HttpServletRequest request, HttpServletResponse response) {
        // 处理错误页面逻辑
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Internal Server Error</h1>");
        out.println("<p>Sorry, something went wrong.</p>");
        out.println("</body></html>");
    }
}

It is important to note that the above methods all require configuring the mapping relationship of the Servlet in web.xml or implementing the javax.servlet.ServletContainerInitializer interface, as well as handling error page logic in the Servlet.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds