4.27.2013

In the previous post I told about how to upload file(image) to the database in J2EE application. Now I want to tell how to show this image on page. My toolkit is the same. So i'll use the Primefaces library for the UI.

A little bit another situation, we need to view the products in the Market. I decided to write a little example, that will show the name, image and description on the page. Other information can be retrieved in the same way. So... let's begin.

The part of the .xhtml page that responsible for the viewing of the information:

<h:form id="product-form">
                                <p:dataGrid var="product" value="#{marketMB.lstProducts}" columns="3"  
                                            rows="12" paginator="true" paginatorPosition="bottom">
                                    <p:panel header="#{product.name}" style="text-align:center">
                                        <h:panelGrid columns="1" style="width:100%">  
                                            <h:graphicImage value="ImageDisplay?product_id=#{product.id}" width="150px" height="150px"/>   

                                            <h:outputText value="#{product.description}" />    
                                        </h:panelGrid>  
                                    </p:panel>
                                </p:dataGrid>

The MarketManagedBean:

@ManagedBean(name="marketMB")
@SessionScoped
public class MarketManagedBean implements Serializable{
    @EJB
    private ProductService productService;
    
    private List lstProducts;
    
    private Product selectedProduct;
    
    public void MarketManagedBean(){}
    
    public void setListOfProducts(){
        lstProducts = (List) productService.getAll();
    }


    /**
     * @return the lstProducts
     */
    public List getLstProducts() {
        setListOfProducts();
        return lstProducts;
    }

    /**
     * @param lstProducts the lstProducts to set
     */
    public void setLstProducts(List lstProducts) {
        this.setLstProducts(lstProducts);
    }

    /**
     * @return the selectedProduct
     */
    public Product getSelectedProduct() {
        return selectedProduct;
    }

    /**
     * @param selectedProduct the selectedProduct to set
     */
    public void setSelectedProduct(Product selectedProduct) {
        this.selectedProduct = selectedProduct;
    }
}
As you can see I am trying to retrieve the list of products using the Service class:

public List getAll() {
        return (List) em.createNamedQuery("Product.findAll").getResultList();
    }
The NamedQuery is described in the Entity class:

@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")
Now let's consider this line:
<h:graphicImage value="ImageDisplay?product_id=#{product.id}" width="150px" height="150px"/>   
The ImageDisplay is the name of the servlet. This servlet is responsible for the image retrieving from the database for the particular product. "product_id" is an Http parameter and it will contain the id of the product. As the result, servlet will retrieve the image from the database for the particular product using the HttpSession parameter "product_id". The code of the servlet:

public class ImageDisplay extends HttpServlet{
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        Statement stmt = null;
        ResultSet rs;
        InputStream sImage;
        try {
 
            String id = request.getParameter("product_id");
            System.out.println("inside servlet–>" + id);
 
            Connection con = Database.getConnection();
            stmt = con.createStatement();
            String strSql = "select image from product where id='" + id + "' ";
            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);
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
As you can see servlet is getting the parameter "product_id" from the Http Request and then it is using in the query to the database.
Then we need to transform retrieved data to the image. The last thing that needed to be considered is web.xml file:

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

0 коммент.:

Subscribe to RSS Feed Follow me on Twitter!