Sunday, July 29, 2007

Printing session attributes and request attributes in JSP for debugging

I generally like to use following JSP which I call req_session_attribute_printer.jsp for debugging purpose. I just include this jsp, where ever i want to debug, i have found this very useful over time for simple debugging.


<%--
req_session_attribute_printer.jsp
Author:<a href="mailto:get.anurag at gmail do com">Anurag Kumar Jain</a>
Date: July 25, 2007
--%>
<%@ page language="java" contentType="text/html; "%>
<script type="text/javascript">
function showHideAttributes(spanId){
if(document.getElementById(spanId).style.display=='block'){
document.getElementById(spanId).style.display='none';
}else if(document.getElementById(spanId).style.display=='none'){
document.getElementById(spanId).style.display='block';

}
}
</script>
<a href="#" onclick="showHideAttributes('debugSpan')"> Attributes</a>
<span id='debugSpan' style='display:none'>
Session Attributes:
<% java.util.Enumeration salist = session.getAttributeNames();
while(salist.hasMoreElements()){
String name=(String)salist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
Request Attributes:
<% java.util.Enumeration ralist = request.getAttributeNames();
while(ralist.hasMoreElements()){
String name=(String)ralist.nextElement();
Object value = session.getAttribute(name);%>
<%=" "+name+"="+value %>
<% }%>
</span>



This is specially very helpful for debugging in environments other than dev, where you have less control.

3 comments:

ThinkFloyd said...

Achcha hai, i like it. But generally programmer has access to dev environment and he can add things to local JSPs... this cant be included and checked in the code.
But for local use itself... this is great tool.
Sahi ja rahe ho Anjain :)

Anurag Jain said...

Yeh true you would still need some amount of permission on other env. But still checkin this code, if needed in any other environment you can just include this page in the page you want to debug remove generated file from cache and refresh the page.

Anurag Jain said...

actually you could also include this in the main page, conditionally depending on some request parameter value, and while debugging pass the appropriate value for the request parameter.