Foros del Web » Programación para mayores de 30 ;) » Java »

JSP y Beans para listar datos de una bd

Estas en el tema de JSP y Beans para listar datos de una bd en el foro de Java en Foros del Web. Hola a todos, Soy novato en J2EE y estoy un poco atascado en los conceptos básicos, tratando de emplear el modelo MVC. Resulta que en ...
  #1 (permalink)  
Antiguo 22/12/2005, 13:31
 
Fecha de Ingreso: diciembre-2005
Ubicación: Madrid, España
Mensajes: 154
Antigüedad: 18 años, 4 meses
Puntos: 2
JSP y Beans para listar datos de una bd

Hola a todos,

Soy novato en J2EE y estoy un poco atascado en los conceptos básicos, tratando de emplear el modelo MVC.

Resulta que en una página web, he de listar en forma de tabla los contenidos de una tabla de la base de datos. Tengo desarrollada una value Bean para representar a una fila de dicha tabla.

Sin embargo, no tengo ni idea de cómo listar todas las filas de esa tabla en la página.

Cosas que se me ocurren:

1) Usar otra value Bean que represente a un conjunto de Beans de la tabla (esto me parece excesivo)

2) Usar SELECTs en la capa de presentación (cosa que me gustaría evitar al máximo)


¿Hay una tercera forma mejor?

Gracias
  #2 (permalink)  
Antiguo 22/12/2005, 14:49
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Lo normal es enviar a la capa de vista una Collection (List, Map, Set) que dentro tendra los Bean que representan cada fila.

Y recorrer esa collection para recuperar cada Bean, creando una fila de tabla por Bean.

Pero bueno, yo no uso JSP sino XSL, asi que quiza voy algo desencaminado
  #3 (permalink)  
Antiguo 16/02/2006, 12:40
Avatar de iceman_cml  
Fecha de Ingreso: diciembre-2005
Ubicación: Rosario
Mensajes: 63
Antigüedad: 18 años, 4 meses
Puntos: 0
ProductBean.java
package jspbook.ch3;
import java.util.*;
import java.sql.*;
public class ProductBean implements java.io.Serializable {
/* Member Variables */
private String prodID;
private String prodDesc;
private String prodManuf;
private float prodPrice;
/* ArrayLists to hold recordsets */
private List prodIDList, prodDescList, prodManufList, prodPriceList;
/* Helper Variables */
private int currentRow;
private int rowCount;
private Connection db = null;
/* Constructor */
public ProductBean() {
/* Initialize bean properties */
setProdID("");
setProdDesc("");
setProdManuf("");
setProdPrice(0.00f);
/* Initialize arrayLists to hold recordsets */
prodIDList = new ArrayList();
prodDescList = new ArrayList();
prodManufList = new ArrayList();
prodPriceList = new ArrayList();
/* Initialize helper variables */
currentRow = 0;
rowCount = 0;
/* Get database connection */
dbConnect();
}
/* Get Database Connection */
private void dbConnect() {
if (db == null) {
try {
Class.forName("org.gjt.mm.mysql.Driver");
db = DriverManager.getConnection("jdbc:mysql://localhost:3306/catalog");
}
catch (Exception e) {
System.out.println("Error Connecting to catalog DB: "+ e.toString());
}
}
}
/* Accessor Methods */
public String getProdID() {
return prodID;
}
public void setProdID(String _prodID) {
prodID = _prodID;
}
public String getProdDesc() {
return prodDesc;
}
public void setProdDesc(String _prodDesc) {
prodDesc = _prodDesc;
}
public String getProdManuf() {
return prodManuf;
}
public void setProdManuf(String _prodManuf) {
prodManuf = _prodManuf;
}
public float getProdPrice() {
return prodPrice;
}
public void setProdPrice(float _prodPrice) {
prodPrice = _prodPrice;
}
/* Read-only attribute */
public int getCurrentRow() {
return currentRow;
}
/* Populate Record List */
public boolean populate() {
/* If prodIDList is empty, then execute the query to populate it */
if (prodIDList.isEmpty()) {
try {
/* Execute Query */
Statement s = db.createStatement();
ResultSet rs = s.executeQuery("select * from product");
prodIDList.clear();
prodDescList.clear();
prodManufList.clear();
prodPriceList.clear();
rowCount = 0;
while (rs.next()) {
prodIDList.add(rs.getString("id"));
prodDescList.add(rs.getString("description"));
prodManufList.add(rs.getString("manuf"));
prodPriceList.add((new Float(rs.getFloat("price"))));
rowCount++;
}
}
catch (Exception e) {
System.out.println("Error populating productBean: "+ e.toString());
return false;
}
}
/* Return status of operation (assume success if it made it this far) */
return true;
}
/* Reset current row */
public void setStartRow(int _start) {
if (_start < rowCount) {
currentRow = _start;
}
}
/* Move to next row */
public int nextRow() {
if (currentRow == rowCount) {
currentRow = 0; // Reset for next page request
return 0; // return 0 to indicate end of recordset
}
/* Populate bean properties with current row */
setProdID((String)prodIDList.get(currentRow));
setProdDesc((String)prodDescList.get(currentRow));
setProdManuf((String)prodManufList.get(currentRow) );
Float price = (Float)prodPriceList.get(currentRow);
setProdPrice(price.floatValue());
currentRow++;
/* return currentRow*/
return currentRow;
}
}

Listing 3-5: productList.jsp
<!-- JSP Directives -->
<%@ page
errorPage="myError.jsp?from=productList.jsp"
%>
<html>
<head>
<title>Product List</title>
</head>
<body>
<basefont face="Arial">
<jsp:useBean id="pBean" scope="session" class="jspbook.ch3.ProductBean"/>
<!-- Build table of products -->
<table align="center" width="600">
<tr>
<td width="20%"><b>Product ID</b></td>
<td width="30%"><b>Description</b></td>
<td width="30%"><b>Manufacturer</b></td>
<td width="20%"><b>Price</b></td>
</tr>
<%
int rowCount = 0;
int startRow = 0;
if (pBean.populate()) {
String start = (String) request.getParameter("start");
if (start != null) {
startRow = new Integer(start).intValue();
pBean.setStartRow(startRow);
}
while (rowCount < 10 && pBean.nextRow() > 0) {
rowCount++;
%>
<tr>
<td width="20%"><jsp:getProperty name="pBean" property="prodID"/></td>
<td width="30%"><jsp:getProperty name="pBean" property="prodDesc"/></td>
<td width="30%"><jsp:getProperty name="pBean" property="prodManuf"/></td>
<td width="20%"><jsp:getProperty name="pBean" property="prodPrice"/></td>
</tr>
<%
}
}
%>
<!-- Display the back and next links -->
<tr>
<td colspan="2" align="center">
<br><a href="?start=<%= (startRow > 9) ? startRow - 10 : 0%>">Back</a>
</td>
<td colspan="2" align="center">
<br><a href="?start=<%= pBean.getCurrentRow() %>">Next</a>
</td>
</tr>
</table>
</body>
</html>
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:27.