• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Retrieving and displaying ResultSet in JSP

 
Terry Chambers
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have built a JSP that can query a database using JDBC and retrieve a ResultSet. I can iterate through that set and display the data out on the page.

I do not want all the Java code exposed on the JSP so I have moved it to a class.

Now I am unsure what is the best method to get the "ResultSet" so that I can display it on the page.

Since a ResultSet object requires executing a Statement, I can't see that I can create a ResultSet object in my JSP code.

I have created a method in my class called "getResultSet". It is current set to a "void" return type.

What is the best way to expose the results of the ResultSet object so that I can access the rows and data elements contained in it, from the JSP?

Do I need to create an object to hold the data from each row and then just create multiple objects? If yes, I am still unsure how I would get the items to display in the HTML of the page.

Thoughts? Advice?

 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Terry Chambers wrote:Do I need to create an object to hold the data from each row and then just create multiple objects? If yes, I am still unsure how I would get the items to display in the HTML of the page.

Thoughts? Advice?



Yes, that's what you need to do. Create an object to hold the data from each row, and build a List of those objects as you read them from the ResultSet. (An ArrayList would be fine for that.)

And don't do any of that in a JSP. Do it all in a servlet. When you have the List filled up, add it as a variable to the request context. Then forward to a JSP. All the JSP should do is to have some JSTL code which gets that variable from the request context and iterates through it. That way it gets each of the objects you extracted from the ResultSet. If you designed the object so that its class has suitable getter methods, you can use JSTL to get the fields from the object and output them, wrapped in suitable HTML.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65119
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul is spot on. Resultsets should never go anywhere near a JSP!

To expand a bit on Paul's post, you'd iterate over the List of objects that capture the data (could be a bean, could be as simple as a string array) using the JSTL's <c:forEach> tag. If your are creating a <table> element to display the info, each iteration would create a new <tr> for the table.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic