Tutorials Logic, IN info@tutorialslogic.com

JSP Error Handling errorPage Custom Error Pages: Causes, Fixes, Examples & Interview Tips

JSP Error Handling errorPage Custom Error Pages

JSP is a practical JSP topic that becomes clear when you connect the definition to a small working example.

Use this page to understand what happens, why it happens, how to verify it, and what mistake usually breaks the concept.

After reading, practice JSP with a normal case, a boundary case, and a broken case so the idea becomes usable instead of memorized.

JSP Error Handling errorPage Custom Error Pages should be studied as a practical Java Server Page lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the java-server-page > error-handling page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

errorPage and isErrorPage Directives

JSP provides two page directives for error handling:

When an exception is thrown on a JSP with errorPage set, the container automatically forwards the request to the designated error page, passing the exception as an attribute.

  • errorPage="url" - Specifies the JSP page to forward to when an unhandled exception occurs on the current page.
  • isErrorPage="true" - Marks a JSP as an error page, enabling access to the exception implicit object.

errorPage and isErrorPage Directives

errorPage and isErrorPage Directives
<%-- divide.jsp: page that may throw an exception --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         errorPage="error.jsp" %>
<!DOCTYPE html>
<html>
<head><title>Division</title></head>
<body>
    <h2>Division Result</h2>
    <%
        int a = Integer.parseInt(request.getParameter("a"));
        int b = Integer.parseInt(request.getParameter("b"));
        // If b == 0, throws ArithmeticException
        // container forwards to error.jsp automatically
        int result = a / b;
        out.println("Result: " + result);
    %>
</body>
</html>

errorPage and isErrorPage Directives

errorPage and isErrorPage Directives
<%-- error.jsp: designated error page --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head><title>Error</title></head>
<body>
    <h2 style="color:red;">An Error Occurred</h2>
    <%-- 'exception' implicit object is available because isErrorPage="true" --%>
    <p><strong>Error Type:</strong> <%= exception.getClass().getName() %></p>
    <p><strong>Message:</strong> <%= exception.getMessage() %></p>
    <p><a href="javascript:history.back()">Go Back</a></p>
</body>
</html>

web.xml Error Mappings

The web.xml deployment descriptor allows you to define global error pages for the entire web application using <error-page> elements. You can map by HTTP error code or by exception type.

web.xml Error Code and Exception Mappings

web.xml Error Code and Exception Mappings
<web-app>

    <!-- Map HTTP 404 to a custom JSP page -->
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/views/error-404.jsp</location>
    </error-page>

    <!-- Map HTTP 500 to a custom JSP page -->
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/views/error-500.jsp</location>
    </error-page>

    <!-- Map a specific exception type -->
    <error-page>
        <exception-type>java.lang.ArithmeticException</exception-type>
        <location>/WEB-INF/views/arithmetic-error.jsp</location>
    </error-page>

    <!-- Catch-all for any unhandled exception -->
    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/WEB-INF/views/generic-error.jsp</location>
    </error-page>

</web-app>

web.xml Error Mappings

web.xml Error Mappings
<%-- WEB-INF/views/error-404.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head><title>404 - Page Not Found</title></head>
<body style="text-align:center; padding:60px;">
    <h1 style="font-size:80px; color:#e74c3c;">404</h1>
    <h2>Page Not Found</h2>
    <p>The page you are looking for does not exist.</p>
    <%-- Access error attributes set by the container --%>
    <%
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String requestUri  = (String)  request.getAttribute("javax.servlet.error.request_uri");
        if (requestUri != null) {
            out.println("<p>Requested URL: <code>" + requestUri + "</code></p>");
        }
    %>
    <a href="${pageContext.request.contextPath}/">Go to Home</a>
</body>
</html>

Exception Implicit Object and Error Attributes

When a JSP is designated as an error page (isErrorPage="true"), the exception implicit object is available. The servlet container also sets several request attributes you can use:

Attribute Description
javax.servlet.error.status_code HTTP status code (Integer)
javax.servlet.error.exception_type Class of the exception (Class)
javax.servlet.error.message Exception message (String)
javax.servlet.error.exception The actual exception object (Throwable)
javax.servlet.error.request_uri URI that caused the error (String)
javax.servlet.error.servlet_name Name of the servlet that caused the error

Custom 500 Error Page with Full Details

Custom 500 Error Page with Full Details
<%-- WEB-INF/views/error-500.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>500 - Internal Server Error</title></head>
<body style="padding:40px;">
    <h1 style="color:#e74c3c;">500 - Internal Server Error</h1>
    <p>Something went wrong on our end. Please try again later.</p>

    <%-- Show details only in development mode --%>
    <%
        String env = application.getInitParameter("environment");
        if ("development".equals(env) && exception != null) {
    %>
        <div style="background:#f8d7da;padding:15px;border-radius:5px;margin-top:20px;">
            <h4>Debug Info (development only):</h4>
            <p><strong>Exception:</strong> <%= exception.getClass().getName() %></p>
            <p><strong>Message:</strong> <%= exception.getMessage() %></p>
            <p><strong>URI:</strong>
               <%= request.getAttribute("javax.servlet.error.request_uri") %></p>
            <pre style="overflow:auto;"><%
                java.io.StringWriter sw = new java.io.StringWriter();
                exception.printStackTrace(new java.io.PrintWriter(sw));
                out.println(sw.toString());
            %></pre>
        </div>
    <% } %>

    <p><a href="${pageContext.request.contextPath}/">Return to Home</a></p>
</body>
</html>

Deep Study Notes for JSP

JSP should be learned as a practical JSP skill, not only as a definition. Start by asking what problem the topic solves, what input or state it receives, what rule it applies, and what visible result proves it worked.

A strong explanation of JSP includes the normal case, a boundary case, and a failure case. When you practice, write down the before-state, the operation, the after-state, and the reason the result changed.

This lesson was expanded because the audit reported: under 650 content words; limited checklist/practice/mistake/FAQ notes . The added notes below focus on clearer explanation, more examples, and concrete practice so the topic is easier to understand from the page itself.

  • Define the exact problem solved by JSP before looking at syntax.
  • Trace one small example by hand and describe every step in plain language.
  • Identify what changes when the input is empty, repeated, invalid, delayed, or larger than expected.
  • Connect the topic to a realistic project scenario instead of treating it as isolated theory.
  • Verify your answer with output, logs, query results, browser behavior, compiler feedback, or a state table.

Worked Explanation: Using JSP Correctly

Imagine you are adding JSP to a small learning project. The first step is to choose the smallest scenario that still shows the main idea. Avoid starting with a large production design; it hides the concept behind too many details.

Next, isolate the moving parts. Name the input, the rule, the output, and the possible error. This habit makes the topic easier to debug because you can see whether the problem is caused by bad data, wrong configuration, incorrect syntax, timing, permissions, or misunderstanding of the rule.

Finally, compare two versions: one correct version and one intentionally broken version. The broken version is valuable because it teaches you how the topic fails in real work, which is usually what interviews and debugging tasks test.

  • Normal case: show the expected behavior with simple, valid input.
  • Boundary case: test the smallest, largest, empty, repeated, or unusual value that still belongs to the topic.
  • Failure case: introduce one realistic mistake and explain the symptom it creates.
  • Repair step: change one thing at a time so you know exactly what fixed the problem.

JSP JSP page example

JSP JSP page example
<%@ page contentType="text/html;charset=UTF-8" %>
<main>
  <h1>JSP</h1>
  <p>Use JSP for the view layer and keep business logic in a servlet or service class.</p>
</main>

JSP servlet-to-JSP flow

JSP servlet-to-JSP flow
request.setAttribute("lessonTitle", "JSP");
request.setAttribute("reviewed", Boolean.TRUE);
request.getRequestDispatcher("/WEB-INF/views/lesson.jsp").forward(request, response);

// The servlet prepares data; the JSP renders it.
Key Takeaways
  • State the purpose of JSP in one sentence before using it.
  • Create a tiny JSP example that demonstrates the topic without unrelated code.
  • Test one normal input, one edge input, and one incorrect input for JSP.
  • Explain the result using before-state, operation, and after-state.
  • Add a verification step such as output, logs, query results, browser behavior, or compiler feedback.
Common Mistakes to Avoid
WRONG Memorizing JSP as a definition only.
RIGHT Pair the definition with a small working example and a failure example.
The fastest way to remember the topic is to explain why the output changes.
WRONG Copying syntax without checking the state before and after.
RIGHT Write the input state, apply the rule, then inspect the output state.
State tracing turns confusing behavior into a visible sequence.
WRONG Ignoring the error path for JSP.
RIGHT Create one intentionally broken version and document the symptom and fix.
A page is much easier to learn from when it explains both success and failure.
WRONG Memorizing JSP Error Handling errorPage Custom Error Pages without the situation where it is useful.
RIGHT Connect JSP Error Handling errorPage Custom Error Pages to a concrete Java Server Page task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Build the smallest working demo for JSP and write what each line does.
  • Change one input or setting and predict the result before running it.
  • Break the example in a realistic way, then fix it and describe the repair.
  • Create a two-column note comparing when to use JSP and when another approach is better.
  • Explain JSP aloud as if teaching a beginner who knows basic JSP only.

Frequently Asked Questions

Understand the problem it solves, the input or state it works on, and the visible result that proves the concept is working.

Use one tiny correct example, one boundary example, and one broken example. Compare the output or state after each change.

They often memorize the term without tracing the behavior. Tracing makes the rule easier to remember and debug.

Remember the problem it solves in Java Server Page, then attach the syntax or steps to that problem.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.