Sunday, 20 March 2011

Serialization In Java

Why Serialization..

Used to send object from one program to other or more generic (from one place to other).

Simple example is from server to client.

How . .

First of all you must have data to send.

It must be object of any type.

We have two sides now..

    1) Source ( will send data (server) )

    2)Destination ( will receive data (client) )

Even the last terms are not correct , in many cases we want bidirectional communication.

    Eg.  Send data from client to server for storing in database ,

    Process some result and send data back to client.

So we can conclude client and server are not appropriate terms , more generic terms will be Sender and Receiver.

At a time client can be sender or receiver (Depends upon the situation and need).

Same for server

So now we are ready to speak technically

First of all to send / communicate between wo medium , we should have a way

  (In fact how can you talk with somebody without a phone)

Lets Do It :

Now we will try to make medium :)

In java that medium is "Stream"

It can be output stream as well as input stream.

Remember we are not categorizing both parties as client and server , but there is

 Java  servlet ( Server) at one end and simple Java class (Client)  at other end.

..(Client side)

First of all for making connection we must have IP address / host address of server.

    (How can you  post  a letter without home address)

Make a http connection using IP address .

Always Try To Take Advantage of OOPS.

So make separate class to make http connection (Remember the chaos of public, protected and private and specially our own default).

Here we go ..


  class for making http connection , all you need to do is call getHttpConnection() methos by passing the address with which you want to make connection.


public class HttpConnection {

    public URLConnection getHttpConnection(String servletUrl) throws MalformedURLException {

        try {


             * Attempt to establish a conncetion to the servlet URL


            URL url = new URL(servletUrl);

            URLConnection connection = url.openConnection(;


             * This connection does both input and output; Therefore set the

             * appropriate flags to true.







             * Set the content type of the Http request to octet-stream as

             * the e-mail message is going to be sent as an Object



          return (connection);

        } catch (Exception e) {


            return (null);





Hey Don’t Be afraid of that large code

It requires two line explanation

Here the code is saying ,

“Please Connect me to given URL (IP address) with some attributes I am telling you”

Here is the one line code

Let previous code class name is HttpConection. connection=null;

Httpconnection createconnection = new HttpConnection();

Connection =  createConnection. getHttpConnection(pass Ip address as string);

Now connection is established , all we need the stream to write or read.

(imagine u have telephone wire till your home but your home telephone is not working)

Suppose you want to send some data / object here to server , u need an object output stream to create and using that you can send.

(equivalent to calling someone and saying hello first)

ObjectOutputStream out=null;

 out = new ObjectOutputStream(connection.getOutputStream());




Now we send our object ( remember String is also an object)

Now one side part is done..

It is upto servlet how does it handle

If u want to handle then have a look :

        ObjectInputStream ois = new ObjectInputStream(request.getInputStream());

        try {

            String receive = (String) ois.readObject();

            System.out.println("received: " + receive);


        } catch (ClassNotFoundException ex) {

            Logger.getLogger(fetchFromDataBase.class.getName()).log(Level.SEVERE, null, ex);



Now suppose servlet make some processing and want to send back data to client

Simple my dear , same concept

Use output stream , Don't worry i won't say you to write ..

ObjectOutputStream objectOutputStream = new ObjectOutputStream(response.getOutputStream());

 objectOutputStream.writeObject( object to write);



Now same thing data is available at client side

What are you thinking (use input stream)

ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());

            Data result = (Data)ois.readObject();


(Data is the type of object we send from servlet , Hey it is not as easy as you are thinking now, there are some precautions )

    Object class must be same on both sides (client and server).
    If possible copy from one side to other, don’t show your art between.
    Caution : package name of the class must be same  in both sides.
    Cast every time you are retrieving object eg.
    Data dataobject = (Data) inputStream.readobject();


you can download ppt from here :

No comments:

Post a Comment