我试图在h:dataTable
中显示名为BOOKS的数据库表中的数据,该表从名为getBooks()
的方法中获取数据。
public ArrayList<Book> getBooks() throws SQLException {
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
PreparedStatement ps = conn.prepareStatement(
"select TITLE, AUTHOR, PRICE from BOOKS"
);
// retrieve customer data from database
ResultSet result = ps.executeQuery();
while (result.next()) {
Book b = new Book();
b.setTitle(result.getString("TITLE"));
b.setAuthor(result.getString("AUTHOR"));
b.setPrice(result.getDouble("PRICE"));
books.add(b);
}
} finally {
conn.close();
}
return books;
}
SQL语句工作正常并且它检索正确的数据,但是当这个JSF页面运行时:
<h:body>
<center>
<h1>Welcome to the Java Bookstore!</h1>
<h:form>
<h3>Inventory List</h3>
<h:dataTable value="#{bookDatabase.books}" var="book" border="5" class="bookList">
<h:column>
<f:facet name="header">Title</f:facet>
<h:outputText value="#{book.title}" />
</h:column>
<h:column>
<f:facet name="header">Author</f:facet>
<h:outputText value="#{book.author}" />
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:outputText value="#{book.price}">
<f:convertNumber currencySymbol="$" groupingUsed="true"
maxFractionDigits="2" type="currency"/>
</h:outputText>
</h:column>
<h:column>
<h:commandLink value="Add to Cart"
action="#{shoppingCart.add(book)}" >
<f:ajax render="@all"/>
</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
<br/>
<br/>
<h3>Shopping Cart</h3>
<h:form>
<h:dataTable value="#{shoppingCart.box}" var="cart" border="5" class="shoppingCart">
<h:column>
<f:facet name="header">Title</f:facet>
<h:outputText value="#{cart.title}" />
</h:column>
<h:column>
<f:facet name="header">Author</f:facet>
<h:outputText value="#{cart.author}" />
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:outputText value="#{cart.price}">
<f:convertNumber currencySymbol="$" groupingUsed="true"
maxFractionDigits="2" type="currency"/>
</h:outputText>
</h:column>
<h:column>
<f:facet name="header">Quantity</f:facet>
<h:outputText value="#{cart.quantity}" />
</h:column>
<h:column>
<h:commandLink value="Remove By One" action="#{shoppingCart.remove(cart)}" >
<f:ajax render="@form" />
</h:commandLink>
</h:column>
</h:dataTable>
<br/>
<h3>
Total Price:
<h:outputText value="#{shoppingCart.getTotal()}">
<f:convertNumber currencySymbol="$" groupingUsed="true"
maxFractionDigits="2" type="currency"/>
</h:outputText>
</h3>
<h:commandButton value="Checkout"
action="#{shoppingCart.checkout}"/>
</h:form>
</center>
</h:body>
它为库存清单显示此表,该清单只应包含4个元素,但似乎迭代次数超过需要,即在到达最后一本书后再次在表格中显示4本书。
为什么它会给我这个bug?我有什么不对的吗?