Friday, February 14, 2014

How To Upload a Image into Database using Jsp, Servlet and Hibernate?


Here is the Way To Upload Image into Database .
In My Example  i have

1.Jsp                                                                          
2.Servlet
3.POJO class
4.DAO Class
5.web.xml
6.hibernate configuration file
and mysql database.

and i am using "commons file uploading library".For This we need 2 jar files

commons-fileupload-(version)[1.3.1].jar
commons-io-(version)[2.4].jar

ImageUpload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>



Image Upload
     
       
ImageUploadServlet.java

package p1;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class ImageUploadServlet extends HttpServlet {

    private static final long serialVersionUID = -1623656324694499109L;
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
    response.setContentType("text/html;charset=UTF-8");
    try {
    if (! ServletFileUpload.isMultipartContent(request)) {
                 System.out.println("sorry. No file uploaded");
                 return;
             }
   
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);

         // parse request
            List items = sfu.parseRequest(request);
         
         // get uploaded file
            FileItem file = (FileItem) items.get(0);
            System.out.println("file size: "+file.getSize());
            new ImageUploadDAO().upload(file.getInputStream());
    }catch(Exception e){
    e.printStackTrace();
    }
    }
}

Image.java(POJO)
package p1;

import java.sql.Blob;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name="image", catalog="TEST")
public class Image {

@Id
@GeneratedValue
@Column(name="id")
private int id;

@Column(name="image")
@Lob
private Blob image;

/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}

/**
* @return the image
*/
public Blob getImage() {
return image;
}

/**
* @param image the image to set
*/
public void setImage(Blob image) {
this.image = image;
}
}

ImageUploadDAO.java


package p1;

import java.io.InputStream;
import java.sql.Blob;

import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class ImageUploadDAO {
private SessionFactory sessionFactory=null;
public void upload(InputStream is){

try{
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
Image image=new Image();
byte[] bytes = IOUtils.toByteArray(is);
Blob blob = Hibernate.createBlob(bytes, session);
image.setImage(blob);
session.save(image);
System.out.println("Image uploded successfully");

}catch(Exception e){
System.err.println("Exception in ImageUploadDAO");
e.printStackTrace();
}
}
}

web.xml

   
    ImageUploadServlet
    ImageUploadServlet
    p1.ImageUploadServlet
 
 
    ImageUploadServlet
    /ImageUploadServlet
 

Hibernate configuration file

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


   
       
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/TEST
        root
        ********
     
        1
        org.hibernate.dialect.MySQLDialect
        thread
   
        true
        update

 
     


This is working example. Enjoy Coding..!!

*Note: if uploading image through Ajax request
add a field fileElementId:'brandimage(image field id in html)', send the remaining data in data:{...} field.
In servlet check the each  'FileItem '  object whether it 'isFormField()'  or not,if yes that is the image ,take InputStream and forward to DAO.There create Blob object and insert into database.It requires ajaxfileupload.js Library along with the commons api in this application.

If You Got any problems  please Feel Free To Make Comments...!!!
Happy coding.

Saturday, February 8, 2014

Activation of Spring Container in Web Application

                                           
One of the ways to Activate Spring 'ApplicationContext'  Container is
First Configure the Spring configuration file in web.xml file
eg:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/Spring.cfg.xml</param-value>
</context-param>


and next Configure the ContextLoaderListener

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
      </listener-class>
</listener>


and finally in Servlet


ApplicationContext context=WebApplicationContextUtils.
getRequiredWebApplicationContext(config.getServletContext());


It is Done. Now ApplicationContext Container will be Activated.

How To Enable Logging Feature in Our Web Application?

One of the ways That we can Enable Logging Functionality in Our Web Applications is as Follows.....
                                                                             
Firstly

we need a file that has all properties related to Logging functionality
Ex:


# Root logger option  
      
   # log4j.rootLogger=INFO, file, stdout  
    log4j.rootLogger=ALL, file, stdout 
      
    # Direct log messages to a log file  
    log4j.appender.file=org.apache.log4j.RollingFileAppender  
    log4j.appender.file.File=/home/imadas/simplrdapilogs/logingFile.log

     #The Maximum size of a backup file.
    log4j.appender.file.MaxFileSize=1MB  

    #To maintain only one backup file.
    log4j.appender.file.MaxBackupIndex=1  

    log4j.appender.file.layout=org.apache.log4j.PatternLayout  
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  
    
    #=======
    # Set the immediate flush to true (default)
    log4j.appender.FILE.ImmediateFlush=true

    # Set the threshold to debug mode
    log4j.appender.FILE.Threshold=debug
    #======
      
    # Direct log messages to stdout  
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
    log4j.appender.stdout.Target=System.out  
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  



Now Configure the above file in application "web.xml"  and Logger Listener  like:

<!-- Log4j Configuration -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- End -->


Now we can use the Logging Feature in Our Application

Logger logger=new Logger.getLogger(The class); 


 Now we can use as we like

logger.info("...");
logger.debug,
logger.error.....etc.