PrimeFaces Carousel Component with Dynamic Image

Building a carousel with the PrimeFaces component is quite easy if you do not embed rich and dynamic content within the carousel. The PrimeFaces User Guide contains an example to get you started. This example will demonstrate how to use the carousel component to enable display of images that could possibly be stored in a database.

MySQL database table structure:

CREATE TABLE `upload_image` (
  `image_id` int(10) unsigned NOT NULL auto_increment,
  `image_name` varchar(45) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY  (`image_id`)
)

We will start by designing the facelet page that will use the carousel component. The code for the facelet is listed below:

dispadv.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>Your Title</title>
    </h:head>
    <h:body>
        <h:outputStylesheet name="css/default.css" />
        <h:form id="banner">
            <p:carousel value="#{tableBean.allImage}" var="product"  autoPlayInterval="4000" effect="fade" circular="true" headerText="Recent Products" style="width:100%" >  
                <h:outputLink value="DisplayImage?Image_id=#{product.imageID}" target="_blank" >
                    <h:panelGrid columns="1" style="width:100%" cellpadding="5">   

                        <p:graphicImage value="DisplayImage?Image_id=#{product.imageID}" width="50" height="50"/>

                        <h:outputText value="Model: #{product.imageID}" />  
                        <h:outputText value="#{product.imageName}"/>  

                    </h:panelGrid>  
                </h:outputLink> 
            </p:carousel> 
        </h:form>


    </h:body>
</html>

The managed bean used to manage the collection of images is listed below:
TableBean.java

package beans;

import dao.Database;
import java.io.Serializable;
import java.sql.*;
import java.util.*;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped

public class TableBean implements Serializable{

    private String imageID;
    private String imageName;
    

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public String getImageLength() {
        return imageLength;
    }

    public void setImageLength(String imageLength) {
        this.imageLength = imageLength;
    }
    private String imageLength;

    public String getImageID() {
        return imageID;
    }

    public void setImageID(String imageID) {
        this.imageID = imageID;
    }
    Connection MySQLcon = null;
    Statement stmt = null;
    PreparedStatement ps;
    ResultSet rs;

    public List<TableBean> getAllImage() {
        List<TableBean> imageInfo = new ArrayList<TableBean>();
        Connection con = Database.getConnection();
        try {
            stmt = con.createStatement();
            String strSql = "select image_id, image_name from upload_image order by image_id ";
            rs = stmt.executeQuery(strSql);
            while (rs.next()) {
                TableBean tbl = new TableBean();
                tbl.setImageID(rs.getString("image_id"));
                tbl.setImageName(rs.getString("image_name"));
                imageInfo.add(tbl);
            }
            con.close();
        } catch (SQLException e) {
            System.out.println("Exception in getAllImage::" + e.getMessage());
        }
        return imageInfo;
    }
}

The servlet class is responsible for serving image requests is listed below:

DisplayImage.java

package beans;

import dao.Database;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayImage extends HttpServlet {

    private static final long serialVersionUID = 4593558495041379082L;

    @Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        Connection MySQLcon = null;
        Statement stmt = null;
        ResultSet rs;
        InputStream sImage;

        try {
            OutputStream output = null;
            String id = request.getParameter("Image_id");
            //System.out.println("inside servlet–>" + id);

            Connection con = Database.getConnection();//maintain the db connection here
            //MySQLcon = lc.getLocalConnection();
            stmt = con.createStatement();
            String strSql = "select image from upload_image where image_id='" + id + "' ";
            //System.out.println("inside servlet Sql–>" + strSql);
            rs = stmt.executeQuery(strSql);
            if (rs.next()) {
                byte[] bytearray = new byte[1048576];
                int size = 0;
                sImage = rs.getBinaryStream(1);
                response.reset();
                response.setContentType("image/jpeg");
                while ((size = sImage.read(bytearray)) != -1) {
                    response.getOutputStream().
                            write(bytearray, 0, size);
                }
            }
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Configure the servlet in web.xml using the following:

    <servlet>
        <description></description>
        <display-name>DisplayImage</display-name>
        <servlet-name>DisplayImage</servlet-name>
        <servlet-class>beans.DisplayImage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DisplayImage</servlet-name>
        <url-pattern>/DisplayImage</url-pattern>
    </servlet-mapping>

Screenshot:
primefaces_carousel

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

13,726` Total Views

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *


− 6 = zero