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>

In this "how to" I'll tell about the process of the uploading file to the database in J2EE project. My toolkit is consist of Netbeans IDE, Glassfish web server, UI library - Primefaces. Let's consider the example with the internet market.

Let's imagine that you have such an entity as a Product. The fields that described in the entity class are: name, description, price and image.

For now the main objective is to add Product to the database.
The part of the .xhtml page that describes the adding to the database:

<h:form enctype="multipart/form-data">

            <p style="font-family: 'Yanone Kaffeesatz';">Choose image for the product</p>
                     <p:fileUpload showButtons="false"
                                value="#{addProductMB.input_file}"
                                mode="simple"   
                                sizeLimit="10000000"   
                                allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>  
                      <br/>
                      <p style="font-family: 'Yanone Kaffeesatz';">Type the name of the product</p>
                      <p:inputText value="#{addProductMB.curproduct.name}"/>
                      <br/><br/>
                      <p style="font-family: 'Yanone Kaffeesatz';">Select the category of the product</p>
                      <p:selectOneMenu value="#{addProductMB.category_name}">
                           <f:selectItem itemLabel="Select One" itemValue="" />  
                           <f:selectItems value="#{addProductMB.category_list}" />
                      </p:selectOneMenu>                             
                      <br/><br/>
                      <p style="font-family: 'Yanone Kaffeesatz';">Type the description of the product</p>
                      <p:inputTextarea value="#{addProductMB.curproduct.description}" cols="50" rows="10"/>
                      <br/><br/>
                      <p style="font-family: 'Yanone Kaffeesatz';">Specify the price of the product</p>
                      <p:spinner min="0" max="2000" maxlength="5" value="#{addProductMB.curproduct.price}"/>
                      <br/><br/>
                      <p:commandButton ajax="false" style="font-family: 'Yanone Kaffeesatz';" 
                                       value="Add product" action="#{addProductMB.addProduct()}"/>
</h:form>
As you can see, I am using the addProductMB as backand bean class. The full name of this class is addProductManagedBean. Let's deal with it:
@ManagedBean(name="addProductMB")
@ViewScoped
public class AddProductManagedBean {
    
    @EJB
    private ProductService productService;
    @EJB
    private CategoryService categoryService;
    private Product curproduct = new Product();
    private UploadedFile input_file;
    private List<String> category_list;
    private String category_name;
    
    public AddProductManagedBean(){}

    private List<String> getCategoryListNames(){
        setCategory_list(categoryService.getCategoryNames());
        return getCategory_list();
    }
    
    
    
    /**
     * @return the productService
     */
    public ProductService getProductService() {
        return productService;
    }

    /**
     * @param productService the productService to set
     */
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * @return the curproduct
     */
    public Product getCurproduct() {
        return curproduct;
    }

    /**
     * @param curproduct the curproduct to set
     */
    public void setCurproduct(Product curproduct) {
        this.curproduct = curproduct;
    }
    
    public void addProduct(){
        if ((curproduct.getName() != null)||(curproduct.getDescription()!=null)){
            String filename = input_file.getFileName().toString();
            String contType = input_file.getContentType();
            String name_cat = this.category_name;
            if (input_file!=null){
            curproduct.setImage(this.input_file.getContents());
            }
            curproduct.setCategory(categoryService.getByName(category_name));
            productService.create(curproduct);
        }
    }

    /**
     * @return the input_file
     */
    public UploadedFile getInput_file() {
        return input_file;
    }

    /**
     * @param input_file the input_file to set
     */
    public void setInput_file(UploadedFile input_file) {
        this.input_file = input_file;
    }

    /**
     * @return the categoryService
     */
    public CategoryService getCategoryService() {
        return categoryService;
    }

    /**
     * @param categoryService the categoryService to set
     */
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * @return the category_name
     */
    public String getCategory_name() {
        return category_name;
    }

    /**
     * @param category_name the category_name to set
     */
    public void setCategory_name(String category_name) {
        this.category_name = category_name;
    }

    /**
     * @return the category_list
     */
    public List<String> getCategory_list() {
        category_list = categoryService.getCategoryNames();
        return category_list;
    }

    /**
     * @param category_list the category_list to set
     */
    public void setCategory_list(List<String> category_list) {
        this.category_list = category_list;
    }
}
The most interesting part of this code is function addProduct(). Let's describe it line-by-line. Firstly, we need to check if the Name and Description were entered on the page. The next step is to retrieve the image that was chosen on the page and upload it to the database. Uploading of the new product's content is proceeding by the entity manager through the service class:

public void create(T entity) {
        getEntityManager().persist(entity);
    }

4.19.2013

In order to describe the picture in detail we need at least two .xhtml pages and one backend bean.

Let's consider that we have two pages with such a content (use any code you wish instead of <...>. I will describe only navigation effect)
 <html>
<h:head>...</h:head>
<h:body>
... 
<a href="index.xhtml">Homepage</a>
<a href="publications.xhtml">Publications</a>
...
</h:body>
<html>

Now we need to transform these lines in something that will show us on wich of the pages we are: Homepage or Publications (e.g.).

Let's create the managed bean, that will contain the following:

@ManagedBean (name="mainMB")
@SessionScoped
public class MainManagedBean {
 
    private String url;
 
    public void MainManagedBean(){}
    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }
    /**
     * @param url the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }
 
    public String getCurrentPage(){
        url = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURI();
        if (url.contains("index.xhtml")){
            return "index";
        } else
return "publs";
}
What actions does the getCurrentPage do? It is simple, in this method we are getting our current URI and checking its content. If its content is like index.xhtml, we need to return "index" string. In another case we need to return "publs" string.
Let's edit the pages:
<html>
<h:head>...</h:head>
<h:body>
... 

 <c:if test="#{mainMB.currentPage!='index'}">
   <a href="index.xhtml">Homepage</a>
</c:if>
<c:if test="#{mainMB.currentPage=='index'}">
   <a style="color:red" href="index.xhtml">Homepage</a> 
</c:if>
<c:if test="#{mainMB.currentPage!='publs'}">
   <a href="publications.xhtml">Publications</a>
</c:if>
<c:if test="#{mainMB.currentPage=='publs'}">
 
   <a style="color:red" href="publications.xhtml">Publications</a> 
</c:if> 
...
</h:body>
<html>
So, that is all. For now you will see the indication of the current page in red color.


Subscribe to RSS Feed Follow me on Twitter!