Link to home
Start Free TrialLog in
Avatar of mkngau
mkngau

asked on

Applet to servlet

Hi,
   I got the problem to send my serializable object from Applet to servlet.
   I used the method recommended from http://www.j-nine.com/pubs/applet2servlet/Applet2Servlet.html
   Anyway, when I run the applet and invoke the method to pass the serializable object to the servlet...nothing seem like to be happen. There is no error message and seem like the servlet have not been invoke by the applet.
   Below is my code in applet (the ContentData is a serializable object)

servlet = new URL("http://mars:7001/CWCreateContentServlet");
           
           servletConnection = servlet.openConnection();
        /** inform the servlet that applet will send the output and accept input */
           servletConnection.setDoInput(true);
           servletConnection.setDoOutput(true);
        /** disable the cache version */
           servletConnection.setUseCaches(false);
           //servletConnection.setDefaultUseCaches(false);
        /** specified the content type */
           //servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
        servletConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        /** send the content object to the servlet using serialization */
           outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
        // serialize the object
           ContentData content = new ContentData(title, dtdPK, xslPK, bXML, status);
           outputToServlet.writeObject(content);
           
           outputToServlet.flush();            
           outputToServlet.close();


and here is the code in my servlet :


ObjectInputStream inputFromApplet = new ObjectInputStream(req.getInputStream());

 ContentData content = null;
inputFromApplet = new ObjectInputStream(req.getInputStream());
                content = (ContentData)(inputFromApplet.readObject());
                inputFromApplet.close();


can anyone tell me what's wrong? Thanks.
Avatar of shyamkumarreddy
shyamkumarreddy
Flag of United States of America image

what is the problem u r getting
any exception

Shyam
Avatar of AGE_Nicolls
AGE_Nicolls

Make sure the code in your Servlet is in the doPost() method, and not in doGet()

AGE_Nicolls

You need to specify the content-length, try
something like this:


Applet Code:


   protected void writeOrder(URLConnection con, Order value)
{
       con.setUseCaches(false);
       con.setDoOutput(true);
       con.setDoInput(true);
       
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       ObjectOutputStream out = new ObjectOutputStream(stream);
       
       out.writeObject(value);
       out.flush();
       
       byte[] buf = stream.toByteArray();
       
       con.setRequestProperty("content-type","application/octet-stream");
       con.setRequestProperty("content-length",""+buf.length);
       
       DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
       
       dataOut.write(buf);
       
       dataOut.flush();
       
       dataOut.close();
}





Here is the code you have to put in your servlet to receive the information:


   public void service(
       HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException
   {

       // Get the session
       HttpSession session = request.getSession(true);

       
       // If the request is a GET method then call the standard GET method
       if (request.getMethod().equals("GET"))
       {
           showPage(request, response);
       }
       else
       {
           String contentType = request.getContentType();
           
           // If we have to stream to client
           if (contentType.equals("application/octet-stream"))
           {
               // Create the output stream
               ObjectInputStream in = new ObjectInputStream(request.getInputStream());
               try{
                   // Read input parameters
                   Order order = (Order) in.readObject();

Just write "servletConnection.connect();" after setDoOutput(true) in your code and try to run your program.  Don't forget to compile it. :-)

servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.connect();
Avatar of mkngau

ASKER

hi venkat2000,
   when I put in the servletConnection.connect();
   I got java.lang.IllegalAccessError: Already connected
   So do you have any idea?
Avatar of mkngau

ASKER

here is the complete servlet.

/*
 * CreateContentServlet.java
 *
 * Created on June 05, 2001, 1:30 AM
 */

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

import javax.ejb.*;
import java.util.*;
import com.pws.dtd.*;
import com.pws.template.*;
import com.pws.contentwriter.*;
import com.common.ContentData;

public class CWCreateContentServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
        HttpSession session     = req.getSession();
        String title            = "";
        String creationDate     = "";
        DtdPK dtdPK             = null;
        TemplatePK templatePK   = null;
        //SitePK sitePK = null;
        //UserPK userPK = null;
        String status           = "";
        byte[] bXML             = null;
       
        try {

            String  customerName = req.getParameter("userType");
 
            ObjectInputStream inputFromApplet = new ObjectInputStream(req.getInputStream());

            ContentData content = null;
            PrintWriter out = null;
           
            if(session.getValue("cw") == null) {
                System.out.println("cw == null");
            } else {
                System.out.println("cw passed");
                ContentWriter cw = (ContentWriter)session.getValue("cw");
                creationDate     = (String)cw.getDate();
                System.out.println("creationDate : "+creationDate);
                inputFromApplet = new ObjectInputStream(req.getInputStream());
                content = (ContentData)(inputFromApplet.readObject());
                inputFromApplet.close();
                System.out.println("Here");
                title  = content.getTitle();

                    System.out.println("title : " + title);
                cw.createContent(title);
                System.out.println("Success!");
               
                    out = new PrintWriter(resp.getOutputStream());
                resp.setContentType("text/plain");
                out.println("passed!");
                out.flush();
                out.close();              
            }  
        } catch(Exception exc) {
            System.out.println("Error CWCreateContentServlet : "+exc);
            System.out.println("fail!");
        }

    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
        doPost(req, resp);
    }
}
Avatar of mkngau

ASKER

here is the codes in the applet :

        ObjectInputStream in;
        URL servlet = null;
        URLConnection servletConnection;
        ObjectOutputStream outputToServlet;
        try{
           System.out.println("Start servlet");
           servlet = new URL("http://mars:7001/CWCreateContentServlet");    
           servletConnection = servlet.openConnection();
        /** inform the servlet that applet will send the output and accept input */
           servletConnection.setDoInput(true);
           servletConnection.setDoOutput(true);
        /** disable the cache version */
           servletConnection.setUseCaches(false);
           servletConnection.setDefaultUseCaches(false);
        /** specified the content type */
           servletConnection.setRequestProperty("content-type", "application/octet-stream");
       
        /** send the content object to the servlet using serialization */
           outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
        // serialize the object
          ContentData content = new ContentData(title);
          if(outputToServlet == null){
            System.out.println("outputToServlet null");
          } else {
            System.out.println("outputToServlet got value");
          }
           outputToServlet.writeObject(content);
           
           outputToServlet.flush();            
           outputToServlet.close();
           System.out.println("title : "+ content.getTitle());
           System.out.println("End servlet");
        } catch (Exception exc) {
            System.out.println("Error create content : " + exc);
        }


and when I run it, I got this out put :


Start servlet
outputToServlet got value
title : testing
End servlet

this mean the code in the applet run fine, not exception been returned. But how come the servlet didn't do anything?
I am not sure about it .. but I would suggest flushing and closing the connection in the applet like
   servletConection.close();
and also to try to comment out the line
  req.getParameter("userType");
in the servlet ...
Avatar of mkngau

ASKER

hi raghbir_banwait,
   what are you mean by the "I would suggest flushing and closing the connection in the applet like
  servletConection.close();"


I have did the same thing in my applet :
outputToServlet.flush();            
          outputToServlet.close();
         
   
I have written a small sample for you to demonstrate applet-servlet communication.

test.html
---------
<html>
<body>
    <applet code="TestApplet.class" width=300 height=300>
    </applet>
</body>
</html>

TestApplet.java
---------------
import java.io.*;
import java.applet.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class TestApplet extends Applet {
     
    public void start() {
        try{
                String s1 = "hello";
                String s2 = "hai";
               
                //Create a URL
                URL url=new URL("http://localhost:8080/examples/servlet/TestServlet");

                //Establish the connection
                URLConnection con= url.openConnection();
                con.setDoInput(true);
                con.setDoOutput(true);
                OutputStream out=con.getOutputStream();

                //Send data to servlet
                ObjectOutputStream oos = new ObjectOutputStream(out);
                oos.writeObject(s1);
                oos.writeObject(s2);
               
                InputStream in =con.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(in);

                //Get reply from servlet
                String reply = ois.readObject().toString();

                //Show the corresponding message or redirect the user to the
                //next page.
               
                System.out.println("the reply is: " + reply);
               
                oos.close();
                ois.close();
         } catch (ConnectException ce) {
                System.out.println("Connection Refused.\nProblem at Web server.\nTry after some time.");
           }
           catch (Exception e){
                System.out.println("Exception while calling Servlet :"+e);
           }
       
        setVisible(true);
    } // end of start()    
} //end of class TestApplet

TestServlet.java
----------------
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet{

    public void init(ServletConfig config) throws ServletException {
        System.out.println("in init");
    } //end of init()

    public void service(HttpServletRequest req, HttpServletResponse res) {
        System.out.println("in service");

        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
       
        try{
            ois = new ObjectInputStream(req.getInputStream());
            oos = new ObjectOutputStream(res.getOutputStream());
             
            //Get the two strings from applet
            String str1 = ois.readObject().toString();
            String str2 = ois.readObject().toString();
           
            oos.writeObject("The two strings are " + str1 + " and " + str2 + ".");
           
            ois.close();
            oos.flush();
            oos.close();
            oos=null;

        } catch(Exception e){
            System.out.println(" Servlet service(): " + e);
            System.out.println("The exception is: " + e.getMessage());
            try{
                oos.writeObject("Error occured at server.\nPlease try later");
            }catch(IOException ioe) {
                System.out.println("IO Exception in error occured"+ioe);
             }
         }
    } //end of service()
} //end of class TestServlet


This example is working fine.  Try to do some changes in the lines of this example.  It will work.
Remember to place the applet class, and the html file in the doc root of your webserver.  Place the servlet in the servlet root.  Change the url for calling the servlet in the applet code and then compile it.

I would suggest a few changes in your code.

Changes in servlet
------------------
1. Use service() method instead of both doGet and doPost for the time being.  Once the servlet starts working, u can play with the methods. i.e., Cut the code in doPost method and paste it in service() method and remove doXXX methods.

2. Now the code is in service() method.  Remove the line "inputFromApplet = new ObjectInputStream(req.getInputStream());" from the else part.

3. Cut the line "out = new PrintWriter(resp.getOutputStream());" from the else block and paste it just after the line "PrintWriter out = null;" and before if statement.

4. Write the line "inputFromApplet.close();" before "out.flush();"

5. Make sure that the servlet url u specified in the applet is correct.  To do so, u can type the servlet url in the browser address bar and press enter.  See whether ur servlet is inited or not.  

I hope, this will help you in solving your problem.
Avatar of mkngau

ASKER

hi venkat2000,
   Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
Avatar of mkngau

ASKER

hi venkat2000,
   Thanks for your help. I have solve my problem. I will award the point to you. by the way, I want to check something with you, is the applet and servlet need to have both the ObjectInputStream and ObjectOutputStream? If missing one, that mean the communication cannot be establish? Thanks.
   
ASKER CERTIFIED SOLUTION
Avatar of venkat2000120699
venkat2000120699

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dear mkngau,

I think your codes are nearly correct, and it will do alright if you add the following line code after you call

outputToServlet.close();

 InputStream in =con.getInputStream();

this line code make the call to servlet actually
Avatar of mkngau

ASKER

hi sontnvn,
   Thanks for your information. Anyway, venkat2000 have help me to solve this problem. See you.


Hi venkat2000,
   Thanks for you help. See you.


regards,
mkngau
thanks for the points :-)