Click to See Complete Forum and Search --> : How to I retrieve records from a db to send to JSP?


decibel
07-19-2009, 05:35 PM
Hello, long time php developer here. I'm used to using the following code to retrieve db records and return an array with the results:


$query = "SELECT * FROM users LIMIT 10";
$result = mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($result)){
array_push($rows, $row);
}
return $rows;


How can i stuff the results into an array from a Java bean to send an array back to JSP for i can iterate through it in JSP? I'm already connected to the db, i can execute queries, and my bean is accessable from my jsp page... i just need to know how to set up the array and return it.

Thanks again.

Kuriyama
07-20-2009, 08:44 AM
I'm not sure if you are using any sort of framework to send queries to your db(ie hibernate), but take a look at result sets.

http://java.sun.com/docs/books/tutorial/jdbc/basics/retrieving.html

JavaServlet
07-21-2009, 07:36 PM
Best way to do this is to use a list.
The JSP can get whatever the servlet gives using the request attribute.

Servlet example:

.....
AddressBook addressBook = new AddressBook();
List addressRows = addressBook.getAllAddresses();
request.setAttribute("addressRows", addressRows);
request.getRequestDispatcher("/WEB-INF/webpage/view.jsp").forward(request, response);
...


Fetch in JSP using an iterator inside a Scriptlet:

<%@ page import="com.mypackage.AddressRowBean" %>
<%@ page import="java.util.*" %>

<jsp:useBean id="addressRows" type="java.util.List" scope="request"/>
<%
for(Iterator it = addressRows.iterator(); it.hasNext(); ){
AddressRowBean row = (AddressRowBean)it.next();
%>
<%= row.getFirstname() %>
<%= row.getLastname() %>
<%
}
%>


or fetch in JSP using more efficient JSTL:

<c:forEach var="row" items="${addressRows}">
${row.firstname}
${row.lastname}
</c:forEach>