How do I display a stack trace on a web page?
Author: Deron Eriksson
Description: This tutorial describes how to format the line separators of a stack trace for display on a web page.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


Normally, a stack trace is displayed on several lines using an operating system's line separator to separate the different lines. However, if this stack trace is displayed on a web page, all the lines will wrap together since a system line separator does not result in any formatting for HTMLW. One way to fix this is to replace all the line separators of a stack trace with <br/> tags. The displayErrorForWeb() method of the TestServlet class below demonstrates this.

TestServlet.java

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

		PrintWriter out = response.getWriter();
		try {
			"test".charAt(20);
		} catch (RuntimeException e) {
			out.println("Stack Trace:<br/>");
			e.printStackTrace(out);
			out.println("<br/><br/>Stack Trace (for web display):</br>");
			out.println(displayErrorForWeb(e));
		}
	}

	public String displayErrorForWeb(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		t.printStackTrace(pw);
		String stackTrace = sw.toString();
		return stackTrace.replace(System.getProperty("line.separator"), "<br/>\n");
	}

}

The TestServlet class first outputs a stack trace with the normal system line separators, and we can see in the web browser output below that all of the lines run together. After that, TestServlet displays the stack trace again, but with the <br> substitutions. We can see that the lower stack trace is much easier to read due to the HTML line break substitutions.

Stack trace results on web page