Tuesday, October 4, 2011

JSP debug code

The following can be pasted into a JSP and then used to display (either in HTML source or in the browser window), the JSP Request, Session, Page, and Application settings for the environment and container the JSP is running within.

I have found this to be a quick useful way to get the lay of the land, when joining a project already in development.




<!--
<%@ page import="java.util.*"%>
<%
Object eobj = request.getParameter("error");
if (eobj != null) {
Exception exception = null;
Object obj = request.getAttribute("exception");
if (obj != null && obj instanceof Exception) {
exception = (Exception) obj;
}
if (exception == null) {
obj = request.getAttribute("javax.servlet.error.exception");
if (obj != null && obj instanceof Exception) {
exception = (Exception) obj;
}
}
if (exception != null) {
%><pre>
<%
exception.printStackTrace(new java.io.PrintWriter(out));
%>
</pre>
<%
}
}
out.println("<h3>Request:</h3><ul>");
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
out.println("<li>HEADER " + name + ": "
+ request.getHeader(name));
}

for (Enumeration e = request.getParameterNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
out.println("<li>PARAM " + name + "="
+ request.getParameter(name) + "</li>");
}

for (Enumeration e = request.getAttributeNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
out.println("<li>ATTRIB " + name + "="
+ request.getAttribute(name) + "</li>");
}
out.println("</ul><h3>Session:</h3><ul>");
for (Enumeration e = session.getAttributeNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
out.println("<li>ATTRIB " + name + "="
+ session.getAttribute(name) + "</li>");
}
out.println("</ul><h3>Page Scope Attributes:</h3><ul>");
for (Enumeration e = pageContext
.getAttributeNamesInScope(pageContext.PAGE_SCOPE); e
.hasMoreElements();) {
String name = (String) e.nextElement();
out.println("<li>ATTRIB "
+ name
+ "="
+ pageContext
.getAttribute(name, pageContext.PAGE_SCOPE)
+ "</li>");
}
out.println("</ul><h3>Application Scope Attributes:</h3><ul>");
for (Enumeration e = pageContext
.getAttributeNamesInScope(pageContext.APPLICATION_SCOPE); e
.hasMoreElements();) {
String name = (String) e.nextElement();
if (name.equals("com.sun.jsp.taglibraryCache")) {
out.print("<li>ATTRIB " + name
+ "= <b>NULL POINTER!</b></li>");
continue;
}
out.print("<li>ATTRIB " + name + "=");
out.println(pageContext.getAttribute(name,
pageContext.APPLICATION_SCOPE)
+ "</li>");
}
out.println("</ul>");
%>
-->

No comments:

About Me

My photo
Lead Java Developer Husband and Father

Tags