Print Java Exception Stacktrace in JSP
This is a very simple way to display the any exception stacktrace in a JSP file, because sometimes we want to display the error on the page , just to see the stacktrace in an easy way , and finding the problem as soon as possible.Well first of all, is better to use a logger to do all this kind of debug in the application , but sometimes we just want to see in the page the error , so here it is a very easy way to display the Excepcion Stacktrace in a JSP File.
Here is the line of code that you need to display the stacktrace in the JSP
- exceptionVariable.printStackTrace(new java.io.PrintWriter(out)); -
And here is a complete JSP file example where you can see the how to see the error. Here the example is just forcing to throw
an Exception by trying to cast a String text “hello” into an int.
<%--
Document : index
Created on : Jul 10, 2009, 11:47:05 AM
Author : neozilon
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
#error {
margin: 5px;
padding: 5px;
background-color: red;
}
</style>
</head>
<body>
<h1>Printing Java Stacktrace in JSP File!</h1>
<%
try{
int test = Integer.parseInt("hola");
}catch(Exception e){
// HERE THE MAGIC BEGINS!!
out.println("<div id=\"error\">");
e.printStackTrace(new java.io.PrintWriter(out));
out.println("</div>");
// THE MAGIC ENDS!!
}
%>
</body>
</html>
I hope this simple snippet will help you, comments about the snippet are welcome.