I have a problem to display a product image stored in the MySQL database as a blob datatype. There are few other things that stored in the product table such as (id,pname,quantity,price,photo). I don't have any problem to show the (id,pname,quantity,price) value from the product table in the jsp except the value from photo column. Below is the code that I use:
ProductDAO.java
public List<Product> getAllProduct() {
List<Product> productlist = new ArrayList<>();
try {
String sql = "SELECT * FROM products";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product p = new Product();
p.setId(rs.getInt("id"));
p.setPname(rs.getString("pname"));
p.setQuantity(rs.getInt("quantity"));
p.setPrice(rs.getDouble("price"));
p.setPhoto(rs.getBlob("photo"));
productlist.add(p);
}
} catch (SQLException e) {
}
return productlist;
}
view.jsp
<div class="row">
<%
ProductDAO dao = new ProductDAO();
List<Product> productList = dao.getAllProduct();
DecimalFormat priceFormatter = new DecimalFormat("#0.00");
for (Product p: productList) {
%>
<img src="${pageContext.request.contextPath}/images/<%= p.getPhoto()%>" width="200" height="200">
<a><%= p.getPname()%></a>
<span class="item_price">RM<%= priceFormatter.format(p.getPrice())%></span>
</div>
<%
}
%>