Web Hosting Talk







View Full Version : Passing Array from Javabean to JSP page


Vortex-Steve
02-27-2006, 06:38 PM
Hey guys,

I've decide to expand my knowledge of web based technology and have gone with Java/JSP to start with. As I'm so new to it this may be a stupid question!

I have a simple Javabean which is called from a JSP page. This Javabean then connects to a MySQL database and runs a query. The results of the query are then stored as a string in an array e.g. results[1] = name1, results[2] = name2 ...

This bit works fine and the array is populated as required. My problem is that I want to display the query results back on the JSP page. In the Javabean all that I seem to be allowed to return is results[x] (where X is a number), rather than the whole array. I want to have the whole array passed back to the JSP page so that I can then run a loop to expand and print it out.

I thought this would be easy enough to do, but it seems it is not as easy as expected! I cannot find any examples on the Internet and everything I have tried does not seem to work.

Since I can find no examples I guess that I am doing it all wrong, but I can't find any examples of how to do it the right way either! How should this be done so that I can get all the results back and printed on screen?

Thanks for any help.

stdunbar
02-28-2006, 04:15 PM
You are likely to be better off returning a Collection (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html). That way you can iterate over the collection with an Iterator:


<%
Iterator i = yourBean.getResultsFromDB().iterator();
while (i.hasNext()) {
YourDBResultObject item = (YourDBResultObject)i.next();

// use item
%>


You don't say what your environment is. This is the "raw" way of doing it. Using Struts, the JSP Expression Language, and/or Java Server Faces makes the task of iterating over a Collection much easier.

In the code above I assumed that you were returning a Collection of YourDBResultObject's. This would be an object that might be the columns of each row returned.

Vortex-Steve
02-28-2006, 07:42 PM
That looks like quite a good way to do it. I'll try it out.

Thanks,