Solved

applet-servlet comunication

Posted on 2000-04-21
5
420 Views
Last Modified: 2013-11-24
can i pass directly objects across applet-servlet comm.
i see the httpRequest's getParamaters only strings , so is only strings
are possible ?
similarly , i need to send an object from the servlet to applet and i dont
want to deocde it to a string ..

tia
0
Comment
Question by:nsuresh
5 Comments
 
LVL 3

Expert Comment

by:ovidiucraciun
Comment Utility
1)open a socket, serialize your objects
and send them to the destination.
the reverse is trivial ;)
0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 100 total points
Comment Utility
some old code (used for debugging applet-servelt communications) ...

// applet side

  public synchronized Object talkToServer(Serializable obj) throws GeneralException
  {
    Object result = null;
 
    try
    {
      Log.debug("talkToServer in");
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      GZIPOutputStream zos = new GZIPOutputStream(bos);
      ObjectOutputStream oo = new ObjectOutputStream(zos);
      oo.writeObject(obj);
      oo.close();

      byte[] data = bos.toByteArray();
      Log.debug("sending " + data.length + " bytes ...");
     
      URLConnection con = servletUrl.openConnection();
     
      con.setDoInput(true);
      con.setDoOutput(true);
      con.setUseCaches(false);

      DataOutputStream out = new DataOutputStream(con.getOutputStream());
      out.writeInt(data.length);
      out.write(data);
      out.flush();
      out.close();
     
      Log.debug("data sent");

//      ObjectOutputStream objectOutput = new ObjectOutputStream(out);
//      objectOutput.writeObject(obj);
//      objectOutput.flush();
//      objectOutput.close();
      try {Thread.sleep(50);} catch (Exception e) {}
     
      Log.debug("receiving data ...");
      DataInputStream din = new DataInputStream(con.getInputStream());
      int len = din.readInt();
      Log.debug("expecting " + len + " bytes ...");
      data = new byte[len];
      din.readFully(data);
     
      Log.debug("got binary data, reading object ...");
      ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream (new ByteArrayInputStream(data)));
      result = objectInput.readObject();
      objectInput.close();
      Log.debug("got object");
    }
    catch (Exception x)
    {
      x.printStackTrace();
      throw(new GeneralException("Communication problem " + x));
    }
    return result;
  }


// servlet side (POST method)

      try
      {
        Log.log("doPost");
        DataInputStream din = new DataInputStream(req.getInputStream());
        int len = din.readInt();
        Log.debug("expecting " + len + " bytes ...");
        byte[] data = new byte[len];
        din.readFully(data);
        Log.debug("read " + len + " bytes");
        Log.debug("reading object ...");
        ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream (new ByteArrayInputStream(data)));
        Object o = objectInput.readObject();
        objectInput.close();
        Log.debug("object read");
       
        if (!isInitialized)
        {
          result = new ErrorResponse("Servlet is not initialized.");
        }
        else if (o instanceof ClientCommandRequest)
        {
          result = server.handleCommand((ClientCommandRequest)o);
        }
        else
        {
          result = new ErrorResponse("Bad request type [" + o.getClass().getName() + "]");
        }
      } catch (Exception x)
      {
        x.printStackTrace();
        result = new ErrorResponse("Server Error: " + x);
      }
     
      Log.debug("sending answer ...");
      // sending answer      
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      GZIPOutputStream zos = new GZIPOutputStream(bos);
      ObjectOutputStream oo = new ObjectOutputStream(zos);
      oo.writeObject(result);
      oo.close();

      byte[] data = bos.toByteArray();
      Log.debug("sending " + data.length + " bytes ...");
     
      DataOutputStream out = new DataOutputStream(resp.getOutputStream());
      out.writeInt(data.length);
      out.write(data);
      out.close();
      Log.debug("all sent");
  }

0
 
LVL 1

Expert Comment

by:raghurani
Comment Utility
Refer to these sites too

1. http://www.j-nine.com/pubs/applet2servlet/index.htm
    Lists articles, books, exampless (lot many) that will answer
    all of your questions.

2. You need to serialize your object before you pass ot from
    applet to servlet and vice versa. Refer to this site for
    more on this :

    http://java.sun.com/docs/books/tutorial/essential/io/providing.html

3. refer to this example for code details
 
   // read serialized objects at the client
   // connect to the servlet
URL studentDBservlet = new URL( servletLocation );
URLConnection servletConnection = studentDBservlet.openConnection();  
                           
// Don't used a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches(false);

// Read the input from the servlet.  
//
// The servlet will return a serialized vector containing
// student entries.
//
inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
studentVector = (Vector) inputFromServlet.readObject();

   ---  server side here ---

//  Listing 4
//
//  Servlet server-side code to send a serialized
//  vector of student objects to an applet.
//
//

public void sendStudentList(HttpServletResponse response, Vector studentVector)
{
     ObjectOutputStream outputToApplet;
     
     try
     {
         outputToApplet = new ObjectOutputStream(response.getOutputStream());
           
         System.out.println("Sending student vector to applet...");
         outputToApplet.writeObject(studentVector);
         outputToApplet.flush();
           
         outputToApplet.close();
         System.out.println("Data transmission complete.");
     }
     catch (IOException e)
     {
       e.printStackTrace();
     }
}


----- server side to read serialized object  ----

//  Listing 3
//
//  Servlet server-side code to read a serialized
//  student object from an applet.
//
//  The servlet code handles a POST method
//
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
           throws ServletException, IOException
{
    ObjectInputStream inputFromApplet = null;
    Student aStudent = null;        
    PrintWriter out = null;
    BufferedReader inTest = null;
       
    try
    {  
        // get an input stream from the applet
        inputFromApplet = new ObjectInputStream(request.getInputStream());
           
        // read the serialized student data from applet        
        aStudent = (Student) inputFromApplet.readObject();
       
        inputFromApplet.close();

        // continue the process for registering the student object

    }
    catch(Exception e)
    {
        // handle exception
    }  
}        


---  cliend side code to send serialized object to server ---


//  Listing 2
//
//  Applet client-side code to send a student object
//  to a servlet in a serialized fashion.
//
//  A POST method is sent to the servlet.
//

URL studentDBservlet = new URL( webServerStr );
URLConnection servletConnection = studentDBservlet.openConnection();  

// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);          
servletConnection.setDoOutput(true);
               
// Don't use a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);

// Specify the content type that we will send binary data
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
                                                 
// send the student object to the servlet using serialization
outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
               
// serialize the object
outputToServlet.writeObject(theStudent);
               
outputToServlet.flush();                
outputToServlet.close();

--------------------

good luck :))

wishes,
raghuRani
0
 
LVL 1

Expert Comment

by:yogeshr
Comment Utility
Here is one way of passing object directly across applet-servlet .

At the server side : -
public class A extends HttpServlet{
public Date getDate()
{
return new Date();
}

public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException , IOException
{
if("object".equals(req.getParameter("format")))
{
  ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
out.writeObject(getDate());
}
else
{
PrintWriter out = res.getWriter();
out.println(getDate().toString());
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException , IOException
{
  doGet(req,res);
}
}

At the applet side;
private String getDateUsingHttpObject()
{
try
{
URL url = new URL(getCodeBase(),"/servlet/DaytimeServlet");
HttpMessage msg = new HttpMessage(url);

Properties props = new Properties();
props.put("format","object");

InputStream in = msg.sendGetMessage(props);
ObjectInputStream res = new ObjectInputStream(in);

Object obj = res.readObject();
Date date = (Date)obj;
return date.toString();
}
catch(Exception ev1)
{
ev1.printStackTrace();
return null;
}
}

best Luck,
Yogesh
0
 

Author Comment

by:nsuresh
Comment Utility
thanks a lot
Suresh
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
nestparen challenge 4 55
json example 39 108
word0 challenge 3 55
Impossible to extract MSI from new JAVA releases 2 36
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now