4.27.2013

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);
    }

2 коммент.:

Luis said...

Hello! Thanks for your Post. I have been checking it and I wondering how do you make a connection database?....How are you saving the file in a table? Did you create a query for that?.....I´m working on a project and I need to upload pdf files and store it in a PostgreSQL database. I´m using MyBatis and PrimeFaces with not success. I appreciate your comments.....

Luis said...

Hello! Thanks for your Post. I have been checking it and I wondering how do you make a connection database?....How are you saving the file in a table? Did you create a query for that?.....I´m working on a project and I need to upload pdf files and store it in a PostgreSQL database. I´m using MyBatis and PrimeFaces with not success. I appreciate your comments.....

Subscribe to RSS Feed Follow me on Twitter!