tags:

views:

212

answers:

3

I am currently attempting to modify some open source software in JSP and am unaware of the syntax.

How does one dump a complex variable to the browser using JSP?

A: 

I don't know that there's anything you can do aside from manually run through the variable's properties.

<p>Prop1: <%= var1.prop1 %></p>
<p>Prop2: <%= var1.prop2 %></p>
Stefan Kendall
A: 
<% out.println(variable); %>
Bart J
This relies on `VariableClass` having a `toString()` method that renders its state properly; otherwise you'll be getting back something like `com.mypackage.VariableObject@35F0E3`
ChssPly76
+1  A: 

For any variable and standard output, the variable class must implement the .toString() method. Then, you can send it to the renderized web page through the OutputStream in the HttpServletResponse object by using the <%= variable %>. For the java.lang classes it should be immediate.

For more complex classes, you need to implement the .toString() method:


class A {
   private int x;
   private int y;
   private int z;

   public A(int x, int y, int z) {
       this.x = x;
       this.y = y;
       this.z = z;
   }

   // XXX: this method...
   public String toString() {
       return "x = " + x + "; y = " + y + "; z = " + z;
   }
}

You must know that in JSP is no function/method such as *var_dump()* in PHP or Data::Dumper in Perl. In other case, you can send the output to the server stdout stream, by using System.out.println(), but isn't a recommendable way...

Another option is to implement a static method that outputs all members on a well formatted string by using Java Introspection, but is a known issue that is not recommendable to use Java Introspection in production environments.

daniel
That pretty much covers all the bases, I think. Good answer!
Shawn Grigson