Allow communication between applets on different pages

Source: Internet
Author: User
Java tip 101: an alternative to inter-applet Communication
Learn how to make the applet communicate with each other across frameworks and browser windows

Author Tobias Hill

Summary
You may think that the only option to allow the applet to communicate with each other is to usegetApplet. Unfortunately,getAppletThe method returns only the applet on the same HTML page as the called applet, which limits the way you use the communication between the applet to build an interesting interface. The alternative method described in this tip allows the applet in different frameworks or even different browser windows to call each other's methods.

java.appletPackageAppletContextThe class contains two member methods:getAppletAndgetApplets. By using these two methods, an applet can find other applets and call their methods. To do this, you must meet the following security requirements:

  • These applets come from the same directory on the same server.

  • These applets run on the same page in the same browser window.

This design of security restrictions may be a good reason; however, the latter requirement limits the use of inter-applet communication to create an interesting multi-applet interface.

Consider the following situation:

You just compiled a good stock market transaction Applet and decided to write a good help system for it. You want the help system to be an applet and run it in a different browser framework than the stock market transaction applet. You may make this decision because of the website structure or the need to always display the help system. In addition, you want the help system to turn to the correct information/guidance based on the user's current operations in the stock trading applet (just like the "paper clip" in Microsoft office suites ). You even plan to compile the wizard in the Help system, which can remotely identify issues and remotely execute tasks in the stock market transaction applet.

The ideas in this solution are very good. However, because the two applets are on different pagesAppletContextJava APIs in cannot help you implement this idea-but this technique can help you.

Use appletcontext API
Before explaining the alternative mechanism of inter-applet communication, I will briefly describegetAppletAndgetAppletsHow these two methods work. An applet usesgetAppletYou can find another Applet in the same hmtl page by name.getAppletsYou can find all the applets on the same page. If the two methods are successfully executed, one or moreAppletObject. Once the caller findsAppletObject, it may call thisApplet.

Suppose there is such an HTML code:

    <applet code="Applet1" width="400" height="100" name="app1">
    </applet>
    <br>
    <applet code="Applet2" width="400" height="100" name="app2">
    </applet>
    <br>

By using the name attribute in the applet tag, you can reference a specific Applet in the following way:

Applet theotherapplet = getapplet ("app1 ");
Theotherapplet. anymethod (); // call any public Method

Alternatively, you can use the following code to retrieve all the applets on this page:

Enumeration allappletsonsamepage = getapplets ();
While (allappletsonsamepage. hasmoreelements ()){
Applet appl = (applet) allappletsonsamepage. nextelement ();
Appl. anymethod (); // call any public Method
}

When the called applet retrieves one or several applets on the same HTML page where it is located, it can call the common methods of these applets.

Use static data structure
Unfortunately, the standard method can only communicate with the applet on the same HTML page. Fortunately, you can easily avoid this restriction. The method of cross-page communication between applets is based on the fact that if the codebase of the two applets is the same, even if they are loaded in different browser windows, they also share the same runtime environment. Roughly speaking, codebase is the directory from which the applet is loaded. For more information, see the reference resources below. One link points to a tutorial on codebase.

Because the runtime environment is shared, all applet instances can access static domains and static structures, so that these static domains and structures can be used to transmit information between different applets.

The applet not only stores simple data types such as integers, characters, and strings, but also each applet can set itself (Instance) A reference of is stored in a static domain (possibly in its own class. Any applet can access this domain to obtain references pointing to this instance.

Does this sound complicated? No, not at all. Let me give a simple example. Assume that one of your applets (appleta. Class) is in one framework, and the other applet (appletb. Class) is in another framework, and both of them are loaded from the same codebase.

You want to grant appleta the permission to access the public method of appletb. You must have appletb store one of its own references in a static public domain, as shown below:

Public class appletb {
Public static appletb selfref = NULL; // returns the initial value to zero.

Public void Init (){
// Generate a reference to this instance
Selfref = this;
}
...
}

Now you can access the appletb instance from appleta:

    public class AppletA {
        AppletB theOtherApplet = null;

Public void callappletb (){
// Obtain the static domain, which stores
// Instance pointer.
Theotherapplet = appletb. selfref;

// You can call the instance method later,
// As shown below...
Theotherapplet. repaint ();
}
...
}

This is all we have to do. Because the runtime environment is shared by different applets, this method works even if the applet is not on the same page.

It is worth noting that the above Code does not handle the call tocallAppletBMethod. If this happensselfRefYesnullIn this way, no communication is allowed.

A more common method
Of course, there is also a more general method. You can create a class to store the reference of the applet in the static data structure. You will see laterAppletListClass. If you want other applets to access your own public method's applet instance throughAppletListRegister yourself. FollowAppletContext.getApplet(string name)In, and each registration item is associated with a string. When an applet calls a reference of an applet, this string serves as a keyword.

Generally, the applet is registered as follows:

    public class AppletA {
        public void start() {
            AppletList.register("Stock-trade-applet", this);
            ...
        }
    }

Another applet obtains access to it:

    public class AppletB {
        public void run() {
            AppletA tradeApplet =
                (AppletA) AppletList.getApplet("Stock-trade-applet");
            ...
        }
    }

When the applet stops running, you must note thatAppletListTo cancel registration:

    public void stop() {
        AppletList.remove("Stock-trade-applet");
        ...
    }

AppletListThe complete source code of the class is as follows:

0: import java.util.*;
1: import java.applet.Applet;
2:
3: public class AppletList {
4: private static Hashtable applets = new Hashtable();
5:
6: public static void register(String name, Applet applet) {
7: applets.put(name,applet);
8: }
9:
10: public static void remove(String name) {
11: applets.remove(name);
12: }
13:
14: public static Applet getApplet(String name) {
15: return (Applet) applets.get(name);
16: }
17:
18: public static Enumeration getApplets() {
19: return applets.elements();
20: }
21:
22: public static int size() {
23: return applets.size();
24: }
25: }

For examples of how to use this class, download examplecode.zip from the reference resource.

Limitations
As I mentioned earlier, these applets must be loaded from the same codebase. In addition, if two different copies of the browser are running and the applet is loaded into each copy, the applet may not communicate with each other (depending on the browser version and settings ), because they may no longer share the same runtime environment. However, if the browser itself derives a new browser window, there is no problem.

This technique has been tested on several platforms and several browser versions, but in some configurations, the runtime environment of each applet may be independent. This technique has been tested in the following operating system and browser combinations:

Windows 2000: Internet Explorer 5.0, Internet Explorer 5.5, Netscape Navigator 4.72, opera 4.01
Windows 98: Internet Explorer 4.72, Internet Explorer 5.0, Netscape Navigator 4.02
Mac OS 9: Internet Explorer 4.5, Netscape Navigator 4.5
Red Hat 6.2: Netscape Navigator 4.73

Summary
This tip illustrates an alternative method that allows the applet to communicate with each other. This method uses the Java APIgetApplet()Method is not supported. The knowledge introduced in this article increases the possibility of using an applet as part of a website or intranet-it can be used instead or supplemented.getAppletsMethod.


  Author Profile
Tobias Hill is one of the creators of citerus. Based in Sweden, Tobias Hill is committed to building Internet, Intranet and external network systems on the Java platform. Hill began programming in Java in 1996 and participated in many projects, from self-controlled robot programming to online fireworks postcard production programs.

Reference resources

  • InstructionsAppletListClass Example:
    Examplecode.zip
  • The Java tutorial on applet communication provided by Sun:
    Http://web2.java.sun.com/docs/books/tutorial/applet/appletsonly/iac.html
  • Java tutorials on codebase (in other cases) provided by Sun:
    Http://web2.java.sun.com/docs/books/tutorial/applet/appletsonly/html.html
  • View all previousJava skillsAnd submit your skills:
    Http://www.javaworld.com/javatips/jw-javatips.index.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.