Servlet applet communication

I'm having a problem getting a servlet to answer a call from an applet...in the applet I do something like:
String servlet = "http://192.168.123.148/root/MyServlet.class";
url= new URL(servlet);
conn = url.openConnection();
conn.setUseCaches(false);
in = conn.getContentLength();
String contype = conn.getContentType();
And in the servlet:
java.io.PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("segment",Integer.toString(99));
out.flush();
The problem is I don't get my header back in the applet...and when I look at the content type, its "application/java-vm"...not " text/html"...as I set in the servlet...???

     InputStream urlInput = null;
     HttpURLConnection urlConn =  null;
     URL url = new URL(urlStr);
     urlConn = (HttpURLConnection)url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     urlConn.setRequestMethod("POST");
     urlConn.setRequestProperty("Accept-Language", "en");
     urlConn.setRequestProperty("content-type", "text/xml");
     urlInput = urlConn.getInputStream();

Similar Messages

  • Servlet/Applet communication, data limit?

    I have an applet that uses a servlet as a proxy to load/retrieve images from an Oracle database. I have a problem when trying to retrieve images larger than 9-10kb from the database. When using JDBC from a Java Application I don't have any probelms but through the Applet-Servlet configuration I do.
    I use the following code in the Applet:
    URL url =new URL("http","myserver",myport,"/servlet/MyServlet");
    HttpURLConnection imageServletConn = (HttpURLConnection)url.openConnection();
    imageServletConn.setDoInput(true);
              imageServletConn.setDoOutput(true);
              imageServletConn.setUseCaches(false);
    imageServletConn.setDefaultUseCaches (false);
    imageServletConn.setRequestMethod("GET");
    byte buf[] = new byte[imageServletConn.getContentLength()];
    BufferedInputStream instr = new BufferedInputStream(imageServletConn.getInputStream());
    instr.read(buf);
    Image image = Toolkit.getDefaultToolkit().createImage(buf);
    // then code to display the image
    And the following for the Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/gif");
    byte[] buff = loadImage(); // this method returns a byte array representing the image.
    response.setContentLength(contentLength);//contentLength is the size of the image
    OutputStream os = response.getOutputStream();
    os.write(buff);
    os.close();
    thanks in advance!

    thanks for your replay,
    I tried your suggestion but whatever I do it seems that tha applet only brings the first 5-10k of the image from the servlet. This is the value I get from instr.read() or any other type of read method. The value of bytes is not always the same.
    Now I also have something new. For images greater than 100k or so I get this error:
    java.io.IOException: Broken pipe
         at java.net.SocketOutputStream.socketWrite(Native Method)
         at java.net.SocketOutputStream.socketWrite(Compiled Code)
         at java.net.SocketOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at org.apache.jserv.JServConnection$JServOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at java.io.FilterOutputStream.write(Compiled Code)
         at interorient.DBProxyServlet.doGet(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at org.apache.jserv.JServConnection.processRequest(Compiled Code)
         at org.apache.jserv.JServConnection.run(Compiled Code)
         at java.lang.Thread.run(Compiled Code)
    I am using the Oracle Internet application server (ias 9i) which actualy uses the apache web listener.
    It seems that this servlet-applet communication is really unstable. If you have anything that may help me it will be greatly appriciated. You can even e-mail me at [email protected]
    thanks!

  • Servlet/Applet Communication and JRE Version

    Hey all,
    I have an applet that sends objects back and forth to a servlet. I have heard that there can be issues if the applet and servlet are run under different versions of java, and right now, the applet works from some machines but not others (I've only tested on PCs so far). I posted a question similar to this a month or two ago, and someone suggested I use UIDs. Can anyone give me some detailed information on how I would do this, or something similar to ensure that any version of Java on someone's machine will work ok, or a link to some helpful info? Thanks.

    Thanks mchan0! I think this will be very helpful.

  • Servlet Applet object communication problem???!!!

    Hy folks,
    I need to validate the ability of complex Servlet Applet communication an run into my first pb right at the beginning of my tests. I need to have around 200 Applet clients connect to my servlet and communicate by ObjectInput and ObjectOutput streams. So I wrote a simple Servlet accepting HTTP POST connections that return a Java object. When the java Applet get instantiated, the Object Stream communication workes fine. But when the Applet tries to communicate with the servlet after that, I can not create another communication session with that Servlet, instead I get a 405 Method not allowed exception.
    Summarized:
    - Applet init() instantiate URLConnection with Servlet and request Java object (opening ObjectInput and Output Stream, after receaving object, cloasing streams).
    - When I press a "get More" button on my Applet, I am not able to instantiate a new URLConnection with my servler because of that 405 exception, WHY???
    Here my Servlet code:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
             ObjectInputStream inputFromApplet = null;
             ArrayList transmitContent = null;       
             PrintWriter out = null;
             BufferedReader inTest = null;
             try{               
                   inputFromApplet = new ObjectInputStream(request.getInputStream());           
                     transmitContent = (ArrayList) inputFromApplet.readObject();       
                     inputFromApplet.close();
                     ArrayList toReturn = new ArrayList();                 
                     toReturn.add("One");
                     toReturn.add("Two");
                     toReturn.add("Three");
                     sendAnsweredList(response, toReturn);                 
             catch(Exception e){}        
         public void sendAnsweredList(HttpServletResponse response, ArrayList returnObject){
             ObjectOutputStream outputToApplet;    
              try{
                  outputToApplet = new ObjectOutputStream(response.getOutputStream());          
                  outputToApplet.writeObject(returnObject);
                  outputToApplet.flush();           
                  outputToApplet.close();              
              catch (IOException e){
                     e.printStackTrace();
    }Here my Applet code:
    public void init() {         
             moreStuff.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                       requestMore();
             try{
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");              
                  servletConnection = studentDBservlet.openConnection();      
                   servletConnection.setUseCaches (false);
                   servletConnection.setDefaultUseCaches(false);
                   servletConnection.setDoOutput(true);
                   servletConnection.setDoInput(true);
                   ObjectOutputStream outputToApplet;
                 outputToApplet = new ObjectOutputStream(servletConnection.getOutputStream());          
                 outputToApplet.writeObject(new ArrayList());
                 outputToApplet.flush();           
                 outputToApplet.close(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
                  inputFromServlet.close();
                  outputToApplet.close();             
              catch(Exception e){
                   area = new JTextArea();
                   area.setText("An error occured!!!\n");
                   area.append(e.getMessage());
            getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
            getContentPane().add(moreStuff, BorderLayout.SOUTH);
        private void requestMore(){
             try{              
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");                             
                  servletConnection = studentDBservlet.openConnection(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success2!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
              catch(Exception e){               
                   area.setText("An error occured2!!!\n");
                   area.append(e.getMessage());
        }Can someone help me solv this issue please, this is my first Applet Servlet work so far so I have no idea on how to solve this issue.

    Sorry folks, just found my error. Forgot about the ObjectInputStream waiting on the Servlet side, so of course had a dead look...
    Sorry!

  • Inconsistent Stream responses b/w servlet & applet

    Hi all,
    I am facing problem with my servle/applet communication .I am using serialized object transport b/w the two. I am able to send my object using a URL connection class successfully to the server .
    However having problems while reading the response on the applet .
    It's been so incosistent that I sometimes think of switching over to some activex control instead of an applet .
    I have been struggling with this one for quite sometime . Somebody help to fix this out!
    First to the problem faced by me
    Some times I get StreamCorruptedException saying Input stream does not contain serialized object .
    Some times I get EOFException saying Invalid Header-1.
    Why so much inconsistency when I am passing the same serialzed object CStreamData? Anyone's valueable input is highly appreciated.
    My part of code that reads the object sent from the servlet.
    public CStreamData ReadResObj(CServerRequest oRequest)
    CStreamData objResponse = null;
    isServerRunning = true;
    try {
    URL url = new URL( "http://localhost:8080"+
    "/apps/servlet/MWServer");
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    con.setRequestProperty("CONTENT_TYPE","application/octet-stream");
    con.setDoInput(true);
    con.setDoOutput(true);
    ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(oRequest);
    out.flush();
    out.close();
    ObjectInputStream ois = new ObjectInputStream(con.getInputStream());
    //The exception is thrown here while reading...
    objResponse = (CStreamData)ois.readObject();
    ois.close();
    }catch (Exception e)
    isServerRunning = false;
    return (CStreamData)objResponse;
    return (CStreamData)objResponse;
    }//End of readResObj
    Best rgds,
    prithvi

    It would be interesting to see what's the response of your servlet.
    Mybe the response of your servlet is an error html page
    which of course can't be converted into Object of Type CStreamData.
    You should think about doing some error handling before you try read from the ObjectInputStream an before you think about using ActiveX components.
    for example
    URLConnection con = url.openConnection();
    HttpURLConnection httpConnection;
    try
      URL url = new URL( "http://localhost:8080"+"/apps/servlet/MWServer");
      URLConnection con = url.openConnection();
      httpConnection = (HttpURLConnection)con;
      out.close();
      if(  httpConnection.getResposeCode() == HttpURLConnection.HTTP_OK )
         ObjectInputStream ois = new ObjectInputStream(con.getInputStream());
         objResponse = (CStreamData)ois.readObject();
         ois.close();
    }If you still have problems dump the content of your servlet response
    to the console and tell what you see or post parts of the response.

  • Asp-applet communication(URGENT!!)

    hi,
    i am facing a problem on asp-applet communication. i would like to ask how to pass applet parameters to asp page?my code below doesnt seem to work..
    smsClient.java
    public class smsClient {
    private JOptionPane jOptionPanel = new JOptionPane();
    private dialog dd;
    String str;
    public void executeSend(String smsno, String smsMessage,String user_id){
    String qrysmsno=smsno;
    String qrysmsMessage=smsMessage;
    String qryUserId=user_id;
    try{
    String qry=URLEncoder.encode("smsno")+ "=" + URLEncoder.encode(qrysmsno) + "&";
    qry= qry + URLEncoder.encode("smsMessage")+ "=" + URLEncoder.encode(qrysmsMessage);
    //qry= qry + URLEncoder.encode("user_id")+ "=" + URLEncoder.encode(qryUserId);
    URL url=new URL("http://172.20.34.116:8081/3dcommunity/sendsms.asp?"+qry);
    dialog dd=new dialog();
    //dd.showDialog(qry, "Alert!", JOptionPane.WARNING_MESSAGE);
              URLConnection uc = url.openConnection();
              uc.setDoOutput(true);
              uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
              PrintWriter pw = new PrintWriter(uc.getOutputStream());
              pw.println(str);
              pw.close();
              BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
              String res = in.readLine();
              dd.showDialog(res, "Alert!", JOptionPane.WARNING_MESSAGE);
              in.close();
    /*HttpURLConnection http = (HttpURLConnection)url.openConnection();
         http.setRequestMethod("GET");
         InputStream iStrm = null;
         if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
         iStrm = http.getInputStream();
         int length = (int) http.getContentLength();
         if (length > 0) {
         byte servletData[] = new byte[length];
         iStrm.read(servletData);
         String resultString = new String(servletData);
    dd.showDialog(res, "Alert!", JOptionPane.WARNING_MESSAGE);
         iStrm.close();*/
         catch(MalformedURLException e){
         System.err.println(e);
    dd.showDialog("MalformedURLException", "Alert!", JOptionPane.ERROR_MESSAGE);
         catch(IOException e){
         System.err.println(e);
    dd.showDialog("IOException", "Alert!", JOptionPane.ERROR_MESSAGE);
    sendsms.asp
    <%
         set mySMS = Server.CreateObject("SCSMS.SMS")
         mySMS.Port = "COM3"
    %>
    <%
              mfg = mySMS.Manufacturer
              mdl = mySMS.Model
              if mySMS.Error then
                   response.write mySMS.ErrorMsg
              else
                   response.write "Manufacturer : " & mfg & "<br>"
                   response.write "Model : " & mdl & "<br><br>"
              end if
              smsno=request.queryString("smsno")
              smsMessage=request.queryString("smsMessage")
         mySMS.sendsms smsno, smsMessage
         if mySMS.Error <> 0 then
              'response.write "Failed" & mySMS.ErrorMsg
         else
              response.write "Success"
         end if
    %>

    use the following class for applet to any web site connection (it can be asp, jsp, cgi etc)
    package com.oreilly.servlet;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    * A class to simplify HTTP applet-server communication. It abstracts
    * the communication into messages, which can be either GET or POST.
    * <p>
    * It can be used like this:
    * <blockquote><pre>
    * URL url = new URL(getCodeBase(), "/servlet/ServletName");
    * HttpMessage msg = new HttpMessage(url);
    * // Parameters may optionally be set using java.util.Properties
    * Properties props = new Properties();
    * props.put("name", "value");
    * // Headers, cookies, and authorization may be set as well
    * msg.setHeader("Accept", "image/png"); // optional
    * msg.setCookie("JSESSIONID", "9585155923883872"); // optional
    * msg.setAuthorization("guest", "try2gueSS"); // optional
    * InputStream in = msg.sendGetMessage(props);
    * </pre></blockquote>
    * <p>
    * This class is loosely modeled after the ServletMessage class written
    * by Rod McChesney of JavaSoft.
    * @author <b>Jason Hunter</b>, Copyright &#169; 1998
    * @version 1.3, 2000/10/24, fixed headers NPE bug
    * @version 1.2, 2000/10/15, changed uploaded object MIME type to
    * application/x-java-serialized-object
    * @version 1.1, 2000/06/11, added ability to set headers, cookies,
    and authorization
    * @version 1.0, 1998/09/18
    public class HttpMessage {
    URL servlet = null;
    Hashtable headers = null;
    * Constructs a new HttpMessage that can be used to communicate with the
    * servlet at the specified URL.
    * @param servlet the server resource (typically a servlet) with which
    * to communicate
    public HttpMessage(URL servlet) {
    this.servlet = servlet;
    * Performs a GET request to the servlet, with no query string.
    * @return an InputStream to read the response
    * @exception IOException if an I/O error occurs
    public InputStream sendGetMessage() throws IOException {
    return sendGetMessage(null);
    * Performs a GET request to the servlet, building
    * a query string from the supplied properties list.
    * @param args the properties list from which to build a query string
    * @return an InputStream to read the response
    * @exception IOException if an I/O error occurs
    public InputStream sendGetMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = "?" + toEncodedString(args);
    URL url = new URL(servlet.toExternalForm() + argString);
    // Turn off caching
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    // Send headers
    sendHeaders(con);
    return con.getInputStream();
    * Performs a POST request to the servlet, with no query string.
    * @return an InputStream to read the response
    * @exception IOException if an I/O error occurs
    public InputStream sendPostMessage() throws IOException {
    return sendPostMessage(null);
    * Performs a POST request to the servlet, building
    * post data from the supplied properties list.
    * @param args the properties list from which to build the post data
    * @return an InputStream to read the response
    * @exception IOException if an I/O error occurs
    public InputStream sendPostMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = toEncodedString(args); // notice no "?"
    URLConnection con = servlet.openConnection();
    // Prepare for both input and output
    con.setDoInput(true);
    con.setDoOutput(true);
    // Turn off caching
    con.setUseCaches(false);
    // Work around a Netscape bug
    con.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
    // Send headers
    sendHeaders(con);
    // Write the arguments as post data
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeBytes(argString);
    out.flush();
    out.close();
    return con.getInputStream();
    * Performs a POST request to the servlet, uploading a serialized object.
    * <p>
    * The servlet can receive the object in its <tt>doPost()</tt> method
    * like this:
    * <pre>
    * ObjectInputStream objin =
    * new ObjectInputStream(req.getInputStream());
    * Object obj = objin.readObject();
    * </pre>
    * The type of the uploaded object can be determined through introspection.
    * @param obj the serializable object to upload
    * @return an InputStream to read the response
    * @exception IOException if an I/O error occurs
    public InputStream sendPostMessage(Serializable obj) throws IOException {
    URLConnection con = servlet.openConnection();
    // Prepare for both input and output
    con.setDoInput(true);
    con.setDoOutput(true);
    // Turn off caching
    con.setUseCaches(false);
    // Set the content type to be application/x-java-serialized-object
    con.setRequestProperty("Content-Type",
    "application/x-java-serialized-object");
    // Send headers
    sendHeaders(con);
    // Write the serialized object as post data
    ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(obj);
    out.flush();
    out.close();
    return con.getInputStream();
    * Sets a request header with the given name and value. The header
    * persists across multiple requests. The caller is responsible for
    * ensuring there are no illegal characters in the name and value.
    * @param name the header name
    * @param value the header value
    public void setHeader(String name, String value) {
    if (headers == null) {
    headers = new Hashtable();
    headers.put(name, value);
    // Send the contents of the headers hashtable to the server
    private void sendHeaders(URLConnection con) {
    if (headers != null) {
    Enumeration enum = headers.keys();
    while (enum.hasMoreElements()) {
    String name = (String) enum.nextElement();
    String value = (String) headers.get(name);
    con.setRequestProperty(name, value);
    * Sets a request cookie with the given name and value. The cookie
    * persists across multiple requests. The caller is responsible for
    * ensuring there are no illegal characters in the name and value.
    * @param name the header name
    * @param value the header value
    public void setCookie(String name, String value) {
    if (headers == null) {
    headers = new Hashtable();
    String existingCookies = (String) headers.get("Cookie");
    if (existingCookies == null) {
    setHeader("Cookie", name + "=" + value);
    else {
    setHeader("Cookie", existingCookies + "; " + name + "=" + value);
    * Sets the authorization information for the request (using BASIC
    * authentication via the HTTP Authorization header). The authorization
    * persists across multiple requests.
    * @param name the user name
    * @param name the user password
    public void setAuthorization(String name, String password) {
    String authorization = Base64Encoder.encode(name + ":" + password);
    setHeader("Authorization", "Basic " + authorization);
    * Converts a properties list to a URL-encoded query string
    private String toEncodedString(Properties args) {
    StringBuffer buf = new StringBuffer();
    Enumeration names = args.propertyNames();
    while (names.hasMoreElements()) {
    String name = (String) names.nextElement();
    String value = args.getProperty(name);
    buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
    if (names.hasMoreElements()) buf.append("&");
    return buf.toString();
    }

  • Signed applet communication on Mac

    In Denmark homebanking is goin on the net with NetBank. My bank postulates that Mac users cannot participate, as signed applet communication is not supported on Macs.
    I find it hard to believe an suspect that ActiveX components are the crook here.
    Can anybody confirm my suspicion. Or clear my Bank :-)
    I am Macin' 9.0.4ie - MRJ 2.2.5 . Explorer 5.0 or Netscape 6.0

    The bank probably says that because it doesn't have any Macs to test it on. Signed applets do work on Macs. However, not all of JRE 1.1 may be implemented in NS 4 or IE 5.0.
    I think providing applet only access to Netbanking is a really dumb idea. Fortunately, my bank has not gone the applet route and I can use netbanking services just fine on my Mac with 128 bit encryption.
    If I were you, I would just switch to a bank that is more Mac friendly...

  • Applet - Servlet - Database - Servlet- Applet

    Hi All,
    I am using Oracle8i and IE 5.0. I am trying to retrieve the data from a db table and display it.
    Sequence is as following:
    1. Query passed to the applet.
    2. Servlet excutes this query using JDBC and returns the resultset to applet.
    3. Applet displaysthe results.
    Is there anybody who has a code sample to do this, my id is [email protected] ? I am totally new to java and servlets. I would really appreciate any help.
    Thanks a lot.
    Manuriti
    [email protected]

    I've never dealt with the code to handle the applet portion of what you're trying to do, but I can help you with the servlet stuff.
    Your servlet should contain code to accomplish the following steps:
    1. Load an Oracle JDBC driver into memory.
    2. Open a JDBC connection to the Oracle database.
    3. Create a JDBC Statement object which contains the appropriate Oracle SQL code.
    4. Execute the Statement object, which will return a ResultSet.
    5. Read the ResultSet data.
    6. Pool or close the Statement and Connection objects.
    All of these steps are simple. Here's what they might look like in practice:
    // load the Oracle driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // open the connection
    String cs = "jdbc:oracle:[email protected]:1521:DBNAME"; // connection string
    String userName = "scott";
    String password = "tiger";
    Connection con = DriverManager.getConnection(cs, userName, password);
    // create a Statement object
    Statement stmt = con.createStatement();
    // create a ResultSet object
    ResultSet rs = stmt.executeQuery("select * from DUAL"); // your SQL here
    // INSERT CODE HERE TO READ DATA FROM THE RESULTSET
    // close the Statement object
    stmt.close();
    // close the Connection object
    con.close();
    So that's how you get data from your Oracle database. Now, how do you pass it to your applet? Well, this is hardly trivial. Typically, servlets return an HTML-formatted text stream. It is possible to have an applet communicate with a servlet, but that raises security issues that I don't fully understand. I believe you would have to have your user's browsers set to the lowest possible security settings, otherwise the browser won't let the applet open a socket to a foreign IP, but again, I'm shaky on that one.
    Anywho, let me know if this was of help and if you have more questions on the servlet/applet stuff. I can probably help you with more specific questions,.

  • Inter Applet Communication across frames - Help Needed

    I am trying inter applet communication across frames. For this to happen I am using an intermidiate
    class which registers two applets and whenever any applet needs reference of other applet it gets it
    through this class.
    The page is an important part of a navigation link. So it is loaded many times while traversing through
    the site.
    Every time I load this page the applet does not paint itself (shows grey or background) and the browser
    stops responding. The machine needs to be restarted. This also happens when we keep that page idle for
    a long time (say 2 hours - session does not time out but applet hangs). I have used another thread object
    which is for utility and accesses the applet in the other frame every 10 seconds or so.
    When the applet hangs it does ot throw any exception or JVM error. This happens on certain machines
    evrytime and never on some machines. The applet hangs only in Microsoft IE 5 & 5.5 and never in Netscape
    4.x.
    What could be the problem?
    Can anyone help me with this problem? Its a deadline project and I can't get through.
    Thanks & Regards,
    Rahul

    Try making the register and getter methods of the intermediate class static synchronized. Then register the applets in their start() methods and unregister them in their stop() methods. Call the getter method of the intermediate class wherever you need access to another applet and never cache the instance you get. You may have to also synchronize all your start() and stop() methods to the intermediate class, as well as all methods that perform interapplet communication.
    Tell me what happenned ...

  • Applet to Applet communication in one browser process with 2 windows

    Applet to Applet communication in Same IE process bu in different IE windows
    I have two IE windows
    (1) base window
    (2) child window (created through wondow.open() and hence share the same IE process and same JVM)
    Now I have two applets in one in base window and other is in child window and I want to do applet to applet communication. Since both applets are in different windows so AppletContext will not work and I tried to use custom AppletRegistory class to keep each Applet in static Hashtable. Now here comes the problem, Each applet gets different copy of this static Hashtable. i have tried hard to find the reason why a static varible has multiple copies running in the same JVM. Then my friend told me about something called class loader which is according to him is different for each window. I have tried this with two different iframes but in same window and it works fine and the reason being is that they share the same JVM. But why this fails for different windows althougt they also have same JVM?
    I am using JRE v5 update 7 and IE6 on WIN XP SP2.
    Thanks in advance..

    Try this example :
    Files used :
    1). AppletCom.html
    2). First.java
    3). Second.java
    1).AppletCom.html
    <HTML>
    <BODY bgcolor="#FFFFFF" link="#0000A0" vlink="#000080">
    <LI><H2><I>Inter applet communication Applet</I></H2>
    <applet code=First.class name="theFirst" width=250 height=100></applet>
    <applet code=Second.class width=350 height=100></applet>
    <BR>
    Source First.java Second.java
    <P>
    <HR>
    <i>Last updated 8/5/97 Martin Eggenberger</i>
    <HR>
    </BODY>
    </HTML>
    2). First.java
    import java.awt.*;
    <applet code="First" width="200" height="200">
    </applet>
    public class First extends java.applet.Applet {
    //Variables for UI
    Label lblOutput;
    public void init() {
    //Create the UI
    add(new Label("The First applet."));
    lblOutput = new Label("Click on a button in the Second applet.");
    add(lblOutput);
    public Color getcc()
    return Color.pink;
    public String getnm(int a,int b)
    int cnt=a+b;
    String str;
    str="Sum is :_________"+cnt;
    return str;
    public boolean handleEvent(Event event) {
    if ("One".equals(event.arg)) {
    lblOutput.setText("You clicked: One");
    return true;
    } else if ("Two".equals(event.arg)) {
    lblOutput.setText("You clicked: Two");
    return true;
    } else if ("Three".equals(event.arg)) {
    lblOutput.setText("You clicked: Three");
    return true;
    return super.handleEvent(event); }
    3). Second.java
    import java.awt.*;
    import java.applet.*;
    <applet code="Second.java" width="200" height="200">
    </applet>
    public class Second extends java.applet.Applet {
    //Declare the UI variables
    Button btnOne;
    Button btnTwo;
    Button btnThree;
         Applet f;
    Label lb;
    public void init() {
    //Build the UI
    btnOne = new Button("One");
    add(btnOne);
    btnTwo = new Button("Two");
    add(btnTwo);
    btnThree = new Button("Three");
    add(btnThree);
    lb=new Label("SUNO RE KAHANI TERI MERI SHHHHHHH");
    add(lb);
    setLayout(new FlowLayout());
    // lb.setSize(100,100);
    public boolean handleEvent(Event event) {
    if (event.id == Event.ACTION_EVENT && event.target == btnOne) {
         f = getAppletContext().getApplet(new String("theFirst"));
    First applet1=(First)f;
    // int cnt=applet1.givenum(22,25);
    // String str="Sum is:"+cnt+" Fine";
    String str=applet1.getnm(22,25);
    lb.setText(str);
    Color cl=applet1.getcc();
    setBackground(cl);
    return f.handleEvent(event);
    } else if (event.id == Event.ACTION_EVENT && event.target == btnTwo) {
    f = getAppletContext().getApplet(new String("theFirst"));
    return f.handleEvent(event);
    } else if (event.id == Event.ACTION_EVENT && event.target == btnThree) {
    f = getAppletContext().getApplet(new String("theFirst"));
    return f.handleEvent(event);
    return super.handleEvent(event);
    I had this example, so i am sharing it as it is.. instead of giving you any link for tutorial... hope this helps.
    Regards,
    Hiten

  • Is jre1.4 still support javascript to applet communication?

    is jre1.4 still support javascript to applet communication?
    I can't get the method in applet from javascript in jre1.4. Are there have a different way to communication?

    I have a similiar problem. Left a post in the Signed Applet board. I can get the methods called on my applet when operating over HTTP, but when I am on a page served from HTTPS, the browser chews up memory, goes to 100% processor utilization, and the method is never called. This is with the 1.4 plugin.
    Suppose this is related ?

  • Applet communication with struts servlet

    Hi
    I�ve seen a lot of examples where a Java applet communicates with a servlet.
    I�ve made a web application using Struts, and i would like to know if it is possible to use an applet (View) and send to Stuts some data, I mean, call an action like http://localhost:8080/ViewRoads.do.
    Is it possible? ,Where can I find some examples about?, could anyone explain how would it work?, any good book to read about?.
    Thank you.

    I'm sorry but don't you have a communication source code example between a servlet and an applet that does work ? I'm looking for one of these since Two days already.
    thanks

  • How can I use URLConnection to use applet communication with servlet?

    I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
    ====================the applet code below=========================
    import java.io.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.net.*;
    //I have tested that in applet get data from servlet is OK!
    //Still I will change to test in applet post data to a servlet.
    public class TestDataStreamApplet extends Applet
    String response;
    String baseurl;
    double percentUsed;
    String total;
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    private String encodedValue(String rawValue)
         return(URLEncoder.encode(rawValue));
    =========================The servlet code below=====================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class DataStreamEcho extends HttpServlet
    {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          res.setContentType("text/plain");
          PrintWriter out = res.getWriter();
          Runtime rt = Runtime.getRuntime();
          out.println(rt.freeMemory());
          out.println(rt.totalMemory());
          response.setContentType("text/html; charset=GBK");     
          request.setCharacterEncoding("GBK");
          PrintWriter out = response.getWriter();
          HttpSession session=request.getSession();
          ServletContext application=this.getServletContext();
          String currenturl=(String)session.getAttribute("currenturl");
          out.print(currenturl);
    =============================================================
    I have done up,but I found the program don't run as I have thought.
    Can you help me to find where is wrong?Very thank!

    You are trying to pass the current URL to the servlet
    from the applet, right?
    Well, what I put was correct. Your servlet code is
    trying to read some information from session data.
    request.getInputStream() is not the IP address of
    anything...see
    http://java.sun.com/products/servlet/2.2/javadoc/javax
    servlet/ServletRequest.html#getInputStream()
    Please read
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
    .htmlNo,you all don't understand I.
    I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
    All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
    for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
    Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
    =======================applet=============================
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    con.connect();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    =======================servlet=============================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         response.setContentType("text/html; charset=GBK");
    //request.setCharacterEncoding("GBK");
    PrintWriter out = response.getWriter();
    HttpSession session=request.getSession();
    ServletContext application=this.getServletContext();
    //String currenturl=(String)session.getAttribute("currenturl");
    String currenturl=(String)request.getParameter("currenturl");
    out.print(currenturl);
    File fileName=new File("c:\\noname.txt");
    fileName.createNewFile();
    FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
    //applet to a file for a test.
    byte[] b=currenturl.getBytes();
    f.write(b);
    f.close();
    }

  • Communication between servlet & applet

    Hello everybody,
    Well, I have a problem with my applet/servlet system.
    I Would like my applet to send some queries to the servlet.
    However, I don't know how to link the applet with the servlet (the only way I know is to use "openConnection()", but I don't see how to incorporate my query in the URLConnection (in order to have one, I need openCOnnection, and once it's done, well, the doGet method has already be laucnh, without any parameter to read). In my case, the DoGet methods of the servlet is launched, and of course, the HTTPRequest is almost empty, seeing thath I don't see how to specify the differnets parameters.
    Is thereany simple meaning to make the applet communicate this the servlet, sending strings, and receiving objects (I have already solve the problem of the sending of an object from the servlet to the applet, in the doGet method).
    Thank you very much
    C U

    In the applet html include a servlet parameter.
    <param
    name="servlet"
    value="/SqlServlet" />
    In your applet open a connection to servlet.
    InputStream in = null;
    URLConnection conn = null;
    URL url = null;
    String servlet = getParameter("servlet");
    url = new URL(servlet + "?sql=" + URLEncoder.encode(sql));
    conn = url.openConnection();
    in = conn.getInputStream();

  • Need Help!  Applet Servlet Portlet Communication

    Hi
    My applet need to send a keyWord to let a portlet to do some operations. I know an applet can communicate with a servlet by URLConnection.But how can portlet? Can I consider a portlet as a servlet and let the applet communicate with the portlet like servlet by URLConnection? could you tell me whether this is possible?
    Thanks for your help.

    Hi
    You have a white-space in the codebase, remove it.
    If that doesn't help, make a static html page, test the Applet with it.
    /Tobias - hopes this helps

Maybe you are looking for

  • Order schedule line

    Hi experts, I am going through some documents and couldnot understand somethings..Can anyone share their knowledge about these things.. 1.In our BI,we have two multiproviders..one for 'Orders' and one for 'Order Schedule Line'.......I know the though

  • Do I need 'reactivation'? how to do it? EDGE not working...

    I have a vodafone locked iPhone 3G in India and have subscribed to an EDGE plan for prepaid here in Mumbai. It used to work fine so far now all of a sudden EDGE has simply stopped working. THE dodos at vodafone keep on transferring my call so am sure

  • Need negative quantity non-inventory items on Credit Memo

    Version: (2007A) Description of requirements: (Please provide a detailed description) Our customer issues many invoices with a negative quantity line item for a miscellaneous non-inventory item. These non-inventory items are used to reduce the amount

  • Supplier Group Creation Error  in SRM 7.0

    Hello,   We are on SRM 7.0, SP 9. When creating a root supplier group using tcode PPOCV_BBP in SRM, we are  getting a "DATA_LENGTH_0", "CX_SY_RANGE_OUT_OF_BOUNDS" error in the program "SAPLRHOMDETAIL_PP01". This error happens during the new supplier

  • Microsoft Windows Network: The local device name is already in use.

    I posted in : http://answers.microsoft.com/en-us/windows/forum/windows_7-networking/disconnected-network-drive-error-as-follows-an/9a877c38-5e86-4c34-84c2-427a965577c6?page=2 Error: "An error occurred while reconnecting drive letter to \\network serv