在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中處理錯誤頁面的邏輯。