Share this page 

Send a message from an Applet to another Applet on a different page (this howto is deprecated)Tag(s): DEPRECATED


FirstApplet encodes the message for SecondApplet in the search (or query) section of SecondApplet.html URL. Then SecondApplet decodes the search section of its URL and extract the message coming from FirstApplet.

FirstAppletJ.html

<HTML><HEAD></HEAD><BODY>
<APPLET CODE="FirstAppletJ.class"
        HEIGHT=100
        WIDTH=300>
</APPLET></BODY></HTML>
FirstAppletJ.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class FirstAppletJ extends Applet implements
    ActionListener {
 Button b;
 TextField t;
 public void init() {
  add(new Label("Message to 2nd applet :"));
  add(t= new TextField(20));
  add(b = new Button("Load 2nd applet"));
  b.addActionListener(this);
  }

 public void actionPerformed(ActionEvent ae) {
  if (ae.getSource() == b) {
    try {
     getAppletContext().showDocument
       (new URL(getCodeBase(),
         "SecondAppletJ.html?" + "message="
              + URLEncoder.encode(t.getText())));
     }
    catch (Exception e) {
     e.printStackTrace();
     }
    }
   }
}
SecondAppletJ.html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="SecondAppletJ.class"
        HEIGHT=100
        WIDTH=400>
</APPLET></BODY></HTML>
SecondApplet.java
import java.applet.*;
import java.awt.*;
import java.net.*;

public class SecondAppletJ extends Applet {
 public void init() {
   Label l = new Label("Message from 1st Applet");
   add (l);
   TextField tf = new TextField( 50 );
   add(tf);

   // complete current URL
   String s = getDocumentBase().toString();

   // extract the search (or query) section
   String theMessage = s.substring(s.indexOf('?') + 1);

   // remove message header
   theMessage = theMessage.substring("message=".length());

   // decode the string (incomplete)
   theMessage = theMessage.replace('+',' ');

   /*
        with JDK1.2, the decoding can be done
        with java.net.URLDecoder.decode(theMessage).

      you to convert from a MIME format called "x-www-form-urlencoded"
      to a String
      To convert to a String, each character is examined in turn:
      . The ASCII characters 'a' through 'z',
        'A' through 'Z', and '0'
        through '9' remain the same.
      . The plus sign '+' is converted into a
        space character ' '.
      . The remaining characters are represented by 3-character
        strings which begin with the percent sign,
        "%xy", where xy is the two-digit hexadecimal
        representation of the lower 8-bits of the character.
   */



   tf.setText(theMessage);
   }
}
You can try it here! NOTE : On IE, you must be connected to the Internet

The decoding is incomplete but should be Ok for simple need!

If you need to pass the message via the PARAM tag of the SecondApplet then take a look at this How-to.