在Tomcat中处理错误页面有两种方式:
<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>
@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>");
}
}
需要注意的是,以上方式都需要在web.xml中配置Servlet的映射关系或者实现javax.servlet.ServletContainerInitializer接口,以及在Servlet中处理错误页面的逻辑。