how to display images in dataTable using p:graphicImage in Primefaces

In this tutorial, let us see how to use p:graphicImage within dataTable tag in Primefaces. For example, let us display a list of products with images from a database. You can also visit my earlier tutorial for displaying dynamic images using p:graphicImage tag. 

Now let us see the complete code for displaying list of products with images using p:dataTable tag in primefaces.  Let us start with JSF code using p:dataTable and p:graphicImage

JSF Page (productList.xhtml)

In the above JSF code, productId is passed as parameter to retrieve the corresponding product image from the database.

Now let us write managed bean code associated with the above JSF page

Product.java

The above getter method getProductImage() is called twice by the tag <p:graphicImage> when the JSF page is invoked. First time simply DefaultStreamedContent()  is returned so that the URL for the <img>  tag is generated (If part is executed). Second time actual image is returned and rendered (else part is executed).

DAO code to retrieve binary data from database:
ProductImageDAO.java

DDL to create table structue used in this example:

CREATE TABLE Product
(
productId varchar(10) NOT NULL, productName varchar(100) NOT NULL,
productImage mediumblob, PRIMARY KEY ( productId )
);

Now insert product details with image using the below DML

insert into product values (‘I1’, ‘Samsung Tv’, LOAD_FILE(‘c:/temp/testimages/samsungtv.jpg’));

insert into product values (‘I2’, ‘SONY LED TV’, LOAD_FILE(‘c:/temp/testimages/sonytv.jpg’));

Note: Place the image files to be uploaded in the folder c:/temp/testimages

Now Two records are inserted.

Running the application will result the below output

graphicImage and datatable

Technology used in the project:

JSF 2.2

Primefaces 5.2

Eclipse

Apache Tomcat V7.0

MySQL

Java 1.7

 

Reference:  PrimeFaces GraphicImage and DataTable

You may also like

Leave a Reply

8 Comments on "how to display images in dataTable using p:graphicImage in Primefaces"


Guest
dataSQL
6 months 7 days ago

outstanding article…

Guest
JUAN
6 months 16 days ago

// public List getProductList() throws IOException, SQLException {
//
// return new ProductImageDAO().getProductDetails();
where are implemented??????
good job

Guest
maroo
6 months 19 days ago

Hello .
I have Error with ” getProductDetails();” in Class “Product.java

Guest
Vlad
9 months 20 days ago

Very nice article. Thank you very much !

Guest
Allan Braga
1 year 2 months ago

Doesn’t work here, help me please!