Share

November 26, 2008

Helpful Java Tag to display request and session Attributes on JSP Page

As a java developer who works on JSP pages once a while, i find it very hard to see what is in the request. I used to work on Coldfusion where the server was able to display debug info about the page and objects on the page but that does not exist in java.

Over the years i keep moving a jsp file that i included when i needed to display dbug info... Today i moved that jsp file into a JavaTag ...

Check it out, it might be useful for you also...

1. Create the following Java Class


package com.mycompany.ui.tag;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
* This tag will spit the request data to the page
*
* @author gdawoud
*
*/
public class RequestDebugTag extends TagSupport {

@Override
public int doEndTag() throws JspException {
 try {
  pageContext.getOut().print("<hr />");
  displayAttributeList();
  pageContext.getOut().print("<hr />");
  displaySessionList();
 } catch (IOException e) {
  e.printStackTrace();
 }

 return super.doEndTag();
}

private void displayAttributeList() throws IOException {
 StringBuilder sb = new StringBuilder("Attribute Request List");
 sb.append("<table class='debugTable'>");
 ServletRequest request = pageContext.getRequest();
 
 Enumeration attributes = request.getAttributeNames();
 while (attributes.hasMoreElements()) {
   String name = attributes.nextElement();
   Object value = request.getAttribute(name);
   sb.append("<tr>");
   sb.append("<td>").append(name).append("</td>");
   sb.append("<td>").append(value).append("</td>");
   sb.append("</tr>");
 }

 sb.append("</table>");
 pageContext.getOut().print(sb.toString());
}

private void displaySessionList() throws IOException {
 StringBuilder sb = new StringBuilder("Session Attribute List");
 sb.append("<table class='debugTable'>");
 Enumeration attributes = pageContext.getSession().getAttributeNames();

 while (attributes.hasMoreElements()) {
   String name = attributes.nextElement();
   Object value = pageContext.getSession().getAttribute(name);
   sb.append("<tr>");
   sb.append("<td>").append(name).append("</td>");
   sb.append("<td>").append(value).append("</td>");
   sb.append("</tr>");
 }

 sb.append("</table>");
 pageContext.getOut().print(sb.toString());
}

}

2. add to tag to your tld

 <tag>
    <name>requestDebug</name>
    <tag-class>com.mycompany.ui.tag.RequestDebugTag</tag-class>
    <body-content>empty</body-content>
    <description>add debug data from request</description>
 </tag>

3. add to your JSP page

<XXX:requestDebug/>