Friday, April 13, 2007

Debugging Information passed to a JSP Page

Well, scriptlets inside a JSP page Suck. Alright, I agree!!
But sometimes it is necessary to check what are the parameters in the request or session scopes reaching your jsp page.

I found this code somewhere on the web sometime ago. One day (yeah, right) I will right a version of it using JSTL tags, but for now I allow myself to add this scriptlet in one of the pages that are included everywhere in my system. As I use Struts Tiles in my system, I do have a bottom.jsp page which is included everywhere.

So I leave the debug attribute in false state until I need to debug on page or another. At this moment, all I have to do is turn on the debug information in my page by setting the attribute to true.

Below is the scriptlet and page includes that should be added to the page where you want the debug information to be displayed.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page import="java.util.*" %>
<%@ page import="org.apache.struts.*" %>

<%@ page import="org.apache.struts.util.*" %>
<%@ page import="org.apache.struts.action.*" %>

<%
// Print all attributes in the request object
out.println("<p><b>All Attributes in request scope:</b>");
Enumeration paramNames = request.getAttributeNames();
while (paramNames.hasMoreElements()) {
String name = (String) paramNames.nextElement();
Object values = request.getAttribute(name);
out.println("<br> " + name + ":" + values);
}

// Print all attributes in the session object
out.println("<p><b>All Attributes in session scope:</b>");
paramNames = session.getAttributeNames();
while (paramNames.hasMoreElements()) {
String name = (String) paramNames.nextElement();
Object values = session.getAttribute(name);
out.println("<br> " + name + ":" + values);
}

out.println("<p><b>Data in ActionMessages:</b>");

// Get the ActionMessages
Object o = request.getAttribute(Globals.MESSAGE_KEY);
if (o != null) {
ActionMessages ae = (ActionMessages)o;

// Get the locale and message resources bundle
Locale locale =
(Locale)session.getAttribute(Globals.LOCALE_KEY);
MessageResources messages =
(MessageResources)request.getAttribute
(Globals.MESSAGES_KEY);

// Loop thru all the labels in the ActionMessage's
for (Iterator i = ae.properties(); i.hasNext();) {
String property = (String)i.next();
out.println("<br>property " + property + ": ");

// Get all messages for this label
for (Iterator it = ae.get(property); it.hasNext();) {
ActionMessage a = (ActionMessage)it.next();
String key = a.getKey();
Object[] values = a.getValues();
out.println(" [key=" + key +
", message=" +
messages.getMessage(locale,key,values) +
"]");
}
}
}
%>


No comments: