Solved

Applet to servlet

Posted on 2001-06-13
17
636 Views
Last Modified: 2013-11-24
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.
0
Comment
Question by:mkngau
17 Comments
 
LVL 3

Expert Comment

by:shyamkumarreddy
ID: 6186018
what is the problem u r getting
any exception

Shyam
0
 
LVL 1

Expert Comment

by:AGE_Nicolls
ID: 6186693
Make sure the code in your Servlet is in the doPost() method, and not in doGet()

AGE_Nicolls

0
 
LVL 3

Expert Comment

by:Kobold
ID: 6187990
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();

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Expert Comment

by:venkat2000120699
ID: 6189034
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();
0
 

Author Comment

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

Author Comment

by:mkngau
ID: 6189571
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);
    }
}
0
 

Author Comment

by:mkngau
ID: 6189602
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?
0
 

Expert Comment

by:raghbir_banwait
ID: 6189829
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 ...
0
 

Author Comment

by:mkngau
ID: 6190158
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();
         
   
0
 
LVL 2

Expert Comment

by:venkat2000120699
ID: 6192696
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.
0
 
LVL 2

Expert Comment

by:venkat2000120699
ID: 6192757
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.
0
 

Author Comment

by:mkngau
ID: 6193903
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.
0
 

Author Comment

by:mkngau
ID: 6193904
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.
   
0
 
LVL 2

Accepted Solution

by:
venkat2000120699 earned 200 total points
ID: 6194396
Yes.  U r right.  It needs to have control over both input stream and output stream, before performing an io operation.
0
 

Expert Comment

by:sontnvn
ID: 6201190
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
0
 

Author Comment

by:mkngau
ID: 6208998
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
0
 
LVL 2

Expert Comment

by:venkat2000120699
ID: 6209207
thanks for the points :-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
String array comparison 4 45
Java Restore security prompts not working 10 120
hashmap order 17 40
What is the use of Forwarding Class in java 1 34
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

735 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