How can I print error stack trace in JSP page?

后端 未结 9 2017
说谎
说谎 2020-12-01 17:50

I have set my error page like this in web.xml:

 
  java.lang.Exception
  /erro         


        
相关标签:
9条回答
  • 2020-12-01 18:45

    Or, to avoid using scriptlets in your jsp, use jstl:

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    ...
    
    <c:set var="exception" value="${requestScope['javax.servlet.error.exception']}"/>
    
    <c:if test="${exception != null}">
      <h4>${exception}</h4>
      <c:forEach var="stackTraceElem" items="${exception.stackTrace}">
        <c:out value="${stackTraceElem}"/><br/>
      </c:forEach>
    </c:if>
    

    Ideally, scriptlets should be disallowed as a best practice. Explicitly prevent scriplets in you jsp files via the web.xml configuration:

    <jsp-config>
      <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
      </jsp-property-group>
    </jsp-config>
    
    0 讨论(0)
  • 2020-12-01 18:51

    The following parameters will be set by the container when request is forwarded to the error page.

    • javax.servlet.error.status_code
    • javax.servlet.error.exception
    • javax.servlet.error.message
    • javax.servlet.error.request_uri
    • javax.servlet.error.servlet_name
    • javax.servlet.error.exception_type

    In your error JSP do this,

    <%request.getAttribute("javax.servlet.error.exception").printStackTrace(new java.io.PrintWriter(out))%>;
    

    Or Else If your error page is defined as Error page with Page Directive like,

    <%@ page isErrorPage="true" import="java.io.*"%>
    

    The exception scripting variable will be declared in the JSP. You can printing the scripting variable using a scriptlet using,

    exception.printStackTrace(new java.io.PrintWriter(out));
    

    Or,

    <jsp:scriptlet>
        exception.printStackTrace(response.getWriter())
    </jsp:scriptlet>
    
    0 讨论(0)
  • 2020-12-01 18:53

    Thrown Exception object is available as request attribute with name 'javax.servlet.error.exception'. So, in your JSP, you can write:

    <% request.getAttribute("javax.servlet.error.exception").printStackTrace(new java.io.PrintWriter(out); %>
    
    0 讨论(0)
提交回复
热议问题