Sunday, November 25, 2012

File Uploading in Servlet

File Uploading :


As most of us have already done this file uploading operation As End User but so far we are not familiar with the internal moves of it. The moment we come to servlet level programming of file uploading we get to know How this concept works actually...

File Uploading is nothing but transferring a file from client System to Server System for persistence.

To work with File Uploading Concept of servlet, Servlet API is not capable enough to provide support for it.
There is no such predefine classes and interface to work with.
So In that case we have to take the support of Third Party API like javazoom api.Although there are multiple Third party vendors provide adequate support for file uploading in servlet.

Basically we require following 3 jar file(from javazoom api) to work with file uploading concept of servlet.

1)uploadbean.jar        (Main jar file)
2)cos.jar                    (Dependent jar file)
3)struts.jar                  (Dependent jar file)

Main jar file(uploadbean.jar) should be added to classpath and main & dependent(all 3) jar file should be added to WEB-INF/lib folder of our web application..

Upto here we done with Background preparation now the time is to see the coding part of it.

For a moment if we assume that we are uploading file somewhere At very first glance the picture comes in our mind is.....some html page and textboxeses along with browse button.....

It is very simple to create this html page ...

upload1.html

<html>
       <head>
             <title>Shows How to upload files</title>
       </head>
       <body>
              <form action="test1" method="post" name="upload" enctype="multipart/form-data">
                     Select File 1:<input type="file" name="uploadfile1"><br><br>
                     Select File 2:<input type="file" name="uploadfile2"><br><br>
                                        <input type="submit" value="Upload">
              </form>
      </body>
</html>


method="post"  :

---------------------
Get method does not support file uploading operation so it is mandatory to go with post method here

The following are diffrenet enctype attribute:

a)application/x-www-form-urlencoded
b)multipart/form-data
c)text/plain

if enctype="application/x-www-form-urlencoded"

------------------------------------------------------------------
Then http protocol translates/converts white spaces into "+" symbol and special charecter into hexadecimal value while transferring data/file from client machine to server machine.


if enctype="multipart/form-data"

------------------------------------------------
Here http protocol doesn't apply any conversion it transfers data/file as it is to server..
no changes at all....This is recommended enctype attribute value...

if enctype="text/plain"

-------------------------------------
here http protocol translates/converts white spaces into "+" symbol and does not translate special charecter while transferring data/file to server.


Now we are going to code servlet for this ...

UploadServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javazoom.upload.*;

public class UploadServlet extends HttpServlet
{
           public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
               {
                   try{
                         UploadBean ub=new UploadBean();
                         ub.setFolderstore("c:/store");
                         MultipartFormDataRequest mreq=new MultipartFormDataRequest(req);
                         ub.store(mreq);
                         PrintWriter pw=res.getWriter();
                         pw.println("<h1>File Successfully uploaded </h1>");

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


Line by line understanding of the Above Code
---------------------------------------------------------

UploadBean ub=new UploadBean();


Creating UploadBean class object, it is used for storing the uploaded file in a server storage area.

ub.setFolderstore("c:/store");


Here we are specifying the location where the uploaded file will go..

MultipartFormDataRequest mreq=new MultipartFormDataRequest(req);


To read the file which are uploaded along with the request, we need to convert ServletRequest obj into MultipartFormDataRequest obj...

ub.store(mreq);


To store the uploaded files into a server we need to call store(-) of UploadBean class by passing MultipartFornDataRequest obj as parameter.

In MultipartFormDataRequest there is method getFiles() and it is internally called by store() for reading the uploaded files.

web.xml

<web-app>
            <servlet>
                     <servlet-name>abc</servlet-name>
                     <servlet-class>UploadServlet</servlet-class>
            </servlet>
           <servlet-mapping>
                     <servlet-name>abc</servlet-name>
                     <url-pattern>/test1</url-pattern>
          </servlet-mapping>
</web-app>


Deploymenet directory Structure:


UploadApp
    |------------------WEB-INF
    |                              |---------classes
    |                                              |-------------UploadServlet.java
    |                                              |--------------UploadServlet.class
    |                              |------------web.xml
    |                              |------------lib
    |                                              |-----------uploadbean.jar
    |                                              |-----------cos.jar
    |                                              |-----------struts.jar
    |-----------upload.html



Deploye the following web application in tomcat server and test it with this url

    http://localhost:8080/UploadApp/upload.html

 

You will get this page first





Once we select the file by clicking on the button. and when we click on "Upload"

we'll get this page showing output.





 Now we can check whether this file has successfully Uploaded or not by going to the specify place.
In This example we have taken E:/strore folder....

That's all about Uploading a file in server through Servlet......







  

Saturday, November 24, 2012

Different States Of Hibernate POJO Class Object


3 States of Hibernate POJO class object :
 

1)Transient State                                                                                                 

2)Persistenet State                                                                                    

3)Detached State 

 

As we know already, Hibernate pojo class object contains data and we perforn certain DB operation in order to make this data(object data)  persist/manipulate and etc with DB..


--> Transient State object doesn't contain identity value and also doesn't represent record of the DB table because it is just created object of HB pojo class.


This State is not under the control of ORM S/w.....

-->Persistance State object Contains identity value,represent DB table record/Row and also maintains Synchronization with DB table record.                                                                               This object is required to develope persistance logic.

-->Detached State object contains object value but doesn't represent record & doesn't maintain Synchronzation with DB table record.


Every hibernate Application contains one logical memory called persistance context having persistance State HB pojo class object ...


In the above stuff i have used term Synchrinization and one more identity value.....

 

 

 

Synchrinization:                                                                                                         

*******************

So lets understand what Synchronization  is....


if we do modification on Pojo class object our intention is very clear that it should reflect on DB table record shouldn't it?                                                                                                                      and same thing done with DB table record should reflect on associate pojo class object

So Hibernate S/w gives flexiblity to do this and this is commonly known as Synchrinization...


if we go for definition of synchrinization so it would be something like...

Synchrinization : Modification done on pojo class object will be reflection in the record of DB table and vice versa.... 

 

 

IdentityValue:                                                                                                                           ***************                                                                                                                                

Identity Value is the criteria value/condition value that makes Hibernate s/w to know where(in which row) it has to perform certain DB operation...

otherwise how this Hibernate s/w will come to know that it has to perform operation in this perticular row..????

 For this purpose identity value is requierd...

 

 

 

 

* Programmer configure one or more member variable of HB pojo class as identity field.ORM s/w uses this member variable value as isentity value of HB pojo class object that are representing Db table rows.


*HB s/w internally identifies each HB pojo class object through its identity value & aslo uses that value as criteria /condition value to maintain Synchrinization b/w HB pojo class object and table records.


*HB s/w internally generates update query having identity value as criteria value to reflect the modification done in object to Db table records...(Object to Row Synchronization).


*HB s/w generates select query having identity value as criterai value to reflect the modification done n DB table record to object.. (DB Table record to Object Synchronization)..


Wednesday, November 7, 2012

Sting handling in java

String Handling in JAVA

String Handling is an important part of any programming language.
String
Strings are widely used in JAVA Programming, are a sequence of characters. String Class is defined in java.lang package so it is implicitly available for all programs

String class has following features:-
It is Final class
Due to Final, String class can not be inherited.
It Extends object class.
It implements Serializable, Comparable and CharSequence interfaces.
It is immutable.
It is also a datatype in java

String Example 1:Creating new String
String a=”Ashish”;
String b=new String();
String c=new String(“Ashish”);

String Example 2:Comparing String
String a=”Ashish”;
String b=”Ashish”;
String c=new String(“Ashish”);
if(a==b) System.out.println(“Same reference “);
if(a==c) System.out.println(“Same Reference of A and C “);
else System.out.println(“Not Same Reference “);

There are two ways to create a String object in Java- 
1.Using the new operator. For example,
String str1 = new String("Prateek");.
2.Using a string literal. For example,
String str2="Prateek"; (string literal)

But these both "Prateek" have different reference. So if we compare str1 & str2, this is not equal. because str1 is created using new operator.

This diagram show the difference-




String Class Methods & Example
Click here

StringBuffer Class in JAVA
The java.lang.StringBuffer classes should be used when you have to make a lot of modifications to strings of characters. As,String objects are immutable , so if you choose to do a lot of manipulations with String Objects, you will end up with a lot of abandoned String objects in the String pool.

StringBuffer Example
StringBuffer sb=new StringBuffer(“Hello”);
sb.append(“Hyderabad”);
System.out.println(sb); //HelloHyderabad